Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm in the process of creating unique customers ID's that is an alternative Id for external use. In the process of adding a new column "cust\_uid" with datatype INT for my unique ID's, When I do an INSERT into this new column: ``` Insert Into Customers(cust_uid) Select ABS(CHECKSUM(NEWID())) ``` I get a error: Cou...
For a moment, forget your issue with what must be an attempt to insert into a linked server (though it is not obvious from your code that `Customers` must either be a synonym or you dumbed the statement down). Ask yourself: why would you use random numbers for uniqueness? Random and unique may seem like similar concep...
Again bad choice for generating a unique ID But with that said this does not throw an error so I think something else is going on ``` declare @id int set @id = ABS(CHECKSUM(NEWID())) print @id ``` Your update that you don't want users to know how many accounts and custID is an identity should have been in the orig...
Is INT the correct datatype for ABS(CHECKSUM(NEWID()))?
[ "", "sql", "sql-server", "t-sql", "" ]
I want to export the results of my query to an excel file by clicking on a button in a form. For this I used this code and it works well: ``` Private Sub Command9_Click() On Error GoTo ProcError DoCmd.OutputTo _ ObjectType:=acOutputQuery, _ ObjectName:="Contract Type Billing", _ OutputFormat:=acFormatXLSX, _ Autost...
If you wanted to keep your original parameter query intact you could create a temporary QueryDef to dump the data into a temporary table, and then output the temporary table to Excel: ``` Dim cdb As DAO.Database, qdf As DAO.QueryDef Const tempTableName = "_tempTbl" Set cdb = CurrentDb On Error Resume Next DoCmd.Delete...
I've bump into same problem and instead of using parameters i'd rather insert WHERE criteria in the sql script and export the query result into excel directly (off course you'll have to define a target file). Assuming that date field in Contract Type Billing named dDate. ``` Set qdf = CurrentDb.CreateQueryDef("qTempQu...
Exporting a parameterized query to excel using vba
[ "", "sql", "excel", "vba", "ms-access", "" ]
I've come across this problem numerous times but haven't found a "MySQL way" to solve the issue as such - I have a database that contains **users** and **reports**. Each **report** has an **id** which I display as a **report number** to my users. The main complaint is that users are confused as to why reports have gon...
`MyISAM` supports the second column with auto increment, but **`InnoDB` doesn't**. For InnoDB you might create a trigger `BEFORE INSERT` to get the max value of the reportid and add one to the value. ``` DELIMITER $$ CREATE TRIGGER report_trigger BEFORE INSERT ON reports FOR EACH ROW BEGIN SET NEW.`report_id` = (...
Right one with IFNULL: ``` DELIMITER $$ CREATE TRIGGER salons_trigger BEFORE INSERT ON salon FOR EACH ROW BEGIN SET NEW.salon_id = IFNULL((SELECT MAX(salon_id) + 1 FROM salon WHERE owner = NEW.owner), 1); END $$ DELIMITER ; ```
MySQL second auto increment field based on foreign key
[ "", "mysql", "sql", "database-design", "relational-database", "innodb", "" ]
I have a relation Presidents(firstName,lastName,beginTerm,endTerm) that gives information about US Presidents. Attribute firstName is a string with the first name, and in some cases, one or more middle initials. Attribute lastName is a string with the last name of the president. For example, the previous president has...
Use HAVING instead of WHERE when checking against Group functions. ``` SELECT lastName FROM Presidents WHERE lastName != 'Cleveland' GROUP BY lastName HAVING COUNT(lastName) > 2; ``` However, when solving SQL-puzzles likes this, you should never take into account the actual data. It should work for all consistent dat...
You constrain on aggregates using `HAVING`, and you are also missing a group by. ``` SELECT lastName FROM Presidents where lastName <> 'Cleveland'; group by lastname having COUNT(lastName) > 2 ```
Can I use COUNT() function in the WHERE clause? Query about Presidents
[ "", "sql", "count", "where-clause", "" ]
I have a mysql table with columns `userid` and `createdon` where `createdon` column has `DATE` datatype. ``` --------------------------------------------------------------------------------- ID UserId CreatedOn 1 65 2013-06-...
Try ``` SELECT UserID, MAX(CreatedOn) CreatedOn FROM table1 GROUP BY UserId HAVING CreatedOn < '2013-09-08' ``` Output: ``` | USERID | CREATEDON | |--------|-------------------------------| | 34 | August, 23 2013 00:00:00+0000 | | 54 | July, 03 2013 00:00:00+0000 | ``` Here is **[SQ...
Your expectation is wrong. The first row of the table you posted would meet your criteria (`'2013-06-'13' < '2013-09-08'`). So a resultset with `65,54,34` is as expected. Misunderstood the question. What you want is: ``` SELECT DISTINCT UserId FROM tbl outerTbl WHERE NOT EXISTS ( S...
'NOT GREATER THAN' condition Mysql
[ "", "mysql", "sql", "" ]
I've created a View with a SQL query: ``` CREATE VIEW rightview AS SELECT data.accounts.login,data.accounts.password,data.customers.right_ FROM data.accounts join data.customers using (id); ``` When i cliick on execute the query, it indicates that the View was created successfully. But when I try to display its colu...
IMHO better will be: ``` CREATE VIEW rightview AS SELECT acc.login, acc.password, cust.right_ FROM data.accounts acc LEFT JOIN data.customers cust on acc.id=cust.id ``` if table customers include column ID which is reference to table accounts...
> **Try this one..** ``` CREATE VIEW rightview AS SELECT a.login,a.password,b.right_ FROM accounts a INNER JOIN customers b on a.id = b.id; ``` > **then,** ``` select * from rightview; ``` > **will work..**
Error while displaying a view sql
[ "", "mysql", "sql", "view", "" ]
I have an sql statement from a colleague overseas, but I get a box that pops up when I try to run it that says "Enter Substitution Variable". What do I put in it? My colleague says that they do not get the same box. What causes this message? I am providing the statement below. Any help is greatly appreciated. Also, li...
As @the\_slk said, you can turn off [substitution variables](http://docs.oracle.com/cd/E11882_01/server.112/e16604/ch_five.htm#CACIFHGB) with [`set define off`](http://docs.oracle.com/cd/E11882_01/server.112/e16604/ch_twelve040.htm#SQPUG073). That will stop the client interpreting the `&` in the string `'Passed Review ...
Can you try with "SET DEFINE OFF"? ``` SQL> SET SERVEROUTPUT ON SQL> SET DEFINE OFF SQL> BEGIN 2 DBMS_OUTPUT.PUT_LINE('A&B'); 3 END; 4 / A&B PL/SQL procedure successfully completed. ```
Enter Substitution Variable
[ "", "sql", "oracle", "" ]
I have very limited knowledge of SQL and have tried 4 different similar solutions offered here and I'm still getting error messages. I'm using SQL2005. I want to run a query on a database table (named `plans`) where we store information about students' learning plans. I'd like the query to only grab the most recent p...
``` SELECT A.* FROM [plans] A LEFT OUTER JOIN [plans] B ON B.PlanDate > A.PlanDate AND B.StudentID = A.StudentID WHERE B.PlanID IS NULL ``` This is saying, basically, give me all rows for which there isn't a row with a higher plan date and the same student ID. Another, equivalent way ...
This one assumes that there can be PlanDates in the future and 'most recent' means 'the latest, earlier than today'. ``` WITH CTE AS ( SELECT P.StudentID, MAX(P.PlanDate) AS MostRecentPlanDate FROM plans P WHERE P.PlanDate < GETDATE() GROUP BY P.StudentID ) SELECT P.* FROM plans P ...
Selecting the most current plan for a student
[ "", "sql", "sql-server-2005", "" ]
I have been racking my brain with searching on the internet for the solution, but to no avail, I have been unsuccessful. ``` strSQL = "Update tTbl_LoginPermissions SET LoginName = '" & StrUserName & "', PWD = '" & StrPWD & "', fldPWDDate = '" & Now() & "'" & _ "WHERE intLoginPermUserID = " & MyMSIDColumn0 ``` On...
After much dilberation and help, it turns out the `FindUserName` that utilizes a Win32API function was not trimming the Username appropriately. I changed it to the following: ``` Public Function FindUserName() As String ' This procedure uses the Win32API function GetUserName ' to return the name of the user cu...
Try this: ``` strSQL = "Update tTbl_LoginPermissions SET LoginName = '" & replace(StrUserName, "'", "''") & "', PWD = '" & replace(StrPWD, "'", "''") & "', fldPWDDate = '" & Now() & "'" & _ "WHERE intLoginPermUserID = " & MyMSIDColumn0 ```
Unclosed Quotation mark after the character string 'test'
[ "", "sql", "ms-access", "vba", "" ]
I do not know how to phrase this question so it makes sense but the problem is probably best understood through the example below. My table structured in such a way that an ID can have different row values: ``` PK ID VALUE 1 160487 10122 2 160487 MF 3 166980 10147 4 166980 MF 5 166...
Here is one way with `IN`: ``` select * from yourtable where isnumeric(value) = 1 and id in (select id from yourtable where value = 'mf') ``` * [SQL Fiddle Demo](http://sqlfiddle.com/#!3/848b0/1)
If you always have two records where one has `MF` as value and the other is numeric you can use: ``` SELECT PK, ID, VALUE FROM dbo.TableName t WHERE EXISTS(SELECT 1 FROM dbo.TableName t2 WHERE t2.ID=t.ID AND t2.VALUE='MF') AND ISNUMERIC(t.VALUE) = 1 ``` [**Sql-Fiddle demo**](http://sqlfiddle.com/#!6/b82f...
Filter a table with column values represented as rows
[ "", "sql", "sql-server", "" ]
I have a table with: Name Surname and Outputname ( = Name Surname ) Name and Surname should always have a value, but some time are empty. I need to select from table by surname and i can't use surname field. I can't even change field values with a script because i get this table from an outside source and can be chan...
try this ``` SELECT SUBSTRING_INDEX(Outputname, ' ', -1) as SecondWord FROM USERS WHERE SUBSTRING_INDEX(Outputname, ' ', -1) LIKE 'A%' ORDER BY SecondWord ASC ``` [**demo**](http://sqlfiddle.com/#!2/051fb/1)
One possible approach: ``` SELECT Surname FROM ( SELECT SUBSTRING_INDEX(Outputname, ' ', -1) AS Surname FROM Users) AS S WHERE Surname LIKE 'A%' ORDER BY Surname; ``` [**SQL Fiddle**](http://sqlfiddle.com/#!2/e1d7b/1). This method is based on assumption that Outputname'...
mysql query where second words starts with a letter
[ "", "mysql", "sql", "" ]
I have three tables and i'm trying to return details from 2 of them, however they do not have a direct link, so i have to use a common 3rd table to join them. I'm using SQL developer - Oracle 11g Here is a very simple view of the tables: ``` Country CID | CName ------------- ENG | England FRA | France ...
``` SELECT c.CID, c.CName, r.RegionID, r.RegionName FROM Regions r INNER JOIN Branch b ON b.RegionID = r.RegionID INNER JOIN Countries c ON c.CID = b.CID; ```
This is not how we do join in SQL. You may consider having a look at this simple [reference](http://www.techonthenet.com/sql/joins.php). For your script, whether you need to use mid-table or not; you need to specify which column you are going to link using `ON` phrase. the following could work: ``` SELECT c.cid, ...
Joining 2 tables in SQL using a common third
[ "", "sql", "join", "oracle11g", "inner-join", "" ]
If I were to have these three tables (just an example in order to learn UNION, these are not real tables): **Tables with their columns:** ``` Customer: id | name | order_status Order_Web: id | customer_id | order_filled Order: id | customer_id | order_filled ``` And I wanted to update order\_status in the ...
You do not need a `UNION` for that - replacing an inner join with a pair of outer ones should do it: ``` UPDATE c SET c.order_status = 1 FROM Customer AS c LEFT OUTER JOIN Order_Web As ow ON c.id = ow.customer_id LEFT OUTER JOIN Order As o ON c.id = o.customer_id WHERE ow.order_filled = 1 OR o.order_filled = 1 ``` Yo...
``` UPDATE c SET c.order_status = 1 FROM ( SELECT customer_id FROM order_web WHERE order_filled = 1 UNION SELECT customer_id FROM order WHERE order_filled = 1 ) o JOIN customer c ON c.id = o.customer_id ```
Performing an UPDATE with Union in SQL
[ "", "sql", "sql-update", "union", "" ]
I have a batch file which runs a SQL script in sqlplus and sends the output to a log file: > sqlplus user/pw < RowCount.sql > RowCount.log My log file contains this: ``` Connected to: Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production SQL> SQL> COUNT(*) ---------- 0 SQL> COUNT(*) ------...
You can use `SET ECHO ON` in the beginning of your script to achieve that, however, you have to specify your script using `@` instead of `<` (also had to add `EXIT` at the end): **test.sql** ``` SET ECHO ON SELECT COUNT(1) FROM dual; SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual); EXIT ``` **t...
The **prompt** command will echo text to the output: ``` prompt A useful comment. select(*) from TableA; ``` Will be displayed as: ``` SQL> A useful comment. SQL> COUNT(*) ---------- 0 ```
How to echo text during SQL script execution in SQLPLUS
[ "", "sql", "oracle11g", "sqlplus", "" ]
I have a query that takes 20 min to executed... I remember in one project we used /\*+ PARALLEL(T,8) */ or we would use the with clause and /*+ materialize \*/ and it would make the query responds time really fast withing seconds. How can I do this to this query? ``` select count(*) from ( ...
If you want data then ``` SELECT /*+ PARALLEL(DTL,4) */ HDR.ACCESS_IND, HDR.SID, HDR.CLLI, HDR.DA, HDR.TAPER_CODE, HDR.CFG_TYPE AS CFG_TYPE, HDR.IP_ADDR, HDR.IOS_VERSION, HDR.ADMIN_STATE, HDR.WIRE_CE...
Try this, might be faster: ``` select count(*) from RPT_7330_HDR hdr JOIN LS_DT_MODIFIED LS ON LS.NAME = 'RPT_7330_HDR' AND hdr.DT_MODIFIED = LS.DT_MODIFIED JOIN RPT_7330_DTL dtl on hdr.EID = dtl.EID JOIN CODE_LKUP2 lkup ON LKUP.CODE1 = hdr.ACCESS_IND AND LKUP.CATEGORY='ACCESS_MAPPING' ``` The SQL engine...
SQL shorten responds time using parallel or with clause
[ "", "sql", "performance", "oracle", "" ]
I am trying to have a result 'none' every time it gives me a null result. Right now it is giving me a 0 for a null result. How could I have a row show me 'none' instead of a 0 for a null result. I have tried TO\_CHAR and TO\_NUMBER for the sum and I can't get it to display 'none'... ``` CASE WHEN SUM(ENROLLED) = 0 TH...
Try using the function: COALESCE (cast(sum(expr1) as varchar), 'none') As a side note, I question the use of DISTINCT in your query.
``` CASE WHEN SUM(ENROLLED) = 0 THEN 'none' ELSE SUM(ENROLLED) END AS ENROLLED ``` this returns different types. Make it the same (cast SUM to string)
SQL Error: ORA-00932: inconsistent datatypes: expected CHAR got NUMBER
[ "", "sql", "oracle", "sum", "to-char", "" ]
I am often confronted with such db queries: > Get all entries (e.g. comments) of userX and also all entries of the friends of userX Which is the best way to do this in SQL (MySQL), assuming userX is not friend of himself. **1. Make two queries and merge them later with PHP** ``` a = SELECT * FROM comments W...
One way to do this is to start the query from the user table. Join it with the relation table. Then you can join comments on this with a conditional 'ON' statement. This way MySQL can use the indexes. ``` select c.* from users a left outer join relation friend on a.id = friend.user1_id join comments c on (c.user_id = ...
Why not: ``` SELECT c.* FROM comments WHERE user = X OR user IN ( SELECT user2 FROM relation WHERE user1 = X ) ``` If that's slow, you should look at the execution plan. You might be missing an index.
How to select own entries and entries of friends in one query
[ "", "mysql", "sql", "join", "union", "" ]
I am trying to use MySQL command line client to execute a procedure. The procedure `helloworld()` is executing fine in MySQL query browser. db scheme selected in query browser: ``` DELIMITER $$ DROP PROCEDURE IF EXISTS helloworld$$ CREATE PROCEDURE helloworld() BEGIN SELECT 'helloworld'; END$$ ``` When I `call hello...
Try: /path/to/file/helloworld.sql: ``` USE `yourdb`; DELIMITER $$ DROP PROCEDURE IF EXISTS `helloworld`$$ CREATE PROCEDURE `helloworld`() BEGIN SELECT 'helloworld'; END$$ DELIMITER ; ``` Then from the command line try: ``` Your Mysql connection id is 43 Server Vesion 5.5.24 mysql> SOURCE /path/to/file/hellow...
In my case, the solution was in fact to change the ownership of the source file to be the username of the user who was logging into the machine and running the command via the `mysql` terminal. I am using CentOS Linux with MariaDB/MySQL5.6. The command that worked to remove the error was: `sudo chown username:username...
MySQL Server 5.0 command line client failed to open file .sql
[ "", "mysql", "sql", "stored-procedures", "" ]
Can someone please let me know the issue with the below query? I am running on MS Access and its giving > Syntax error in query expression 'id = @@IDENTITY' Code: ``` public DosageBO SaveDosage(DosageBO dosage) { try { using (IDbConnection connection = OpenConnection()) { StringBuilder sql...
`SELECT @@Identity` is a specialized query. And `@@Identity` is only valid in that context. If you attempt to use `@@Identity` elsewhere, as in a `WHERE` clause, the db engine will throw an error. You will have to retrieve the value from `SELECT @@Identity`, save it, and then use that saved value in your other query.
Remove the `)` at the end ``` WHERE id = @@IDENTITY) ^---here ```
MS Access @@identity query issue
[ "", "sql", "ms-access", "" ]
Little by little I am moving on and understanding sql. Below I have 4 tables. I am trying to work through the “many to many” and “one to many”. Earlier on a similar question I was trying to figure out academies to courses and vice versa. Now it was explained to me that one table was for the course and the other table(a...
In the instructor only teaches at one academy, then it's easy to just have an academy\_id like you have there. If the instructor can teach at different academies, then yes. You should create a table for that: ``` CREATE TABLE academy_instructor ( academy_id int(11) not null, instructor_id int(11) not null , ...
If one each academy has only one instructor then I would consider adding `instructor_id` to the `academy_course` table.
Understanding the use of one-to-many or many-to-many
[ "", "mysql", "sql", "" ]
I am inserting data into a database using millions of insert statements stored in a file. Is it better to insert this row by row or in bulk ? I am not sure what the implications can be. Any suggestions on the approach ? Right now, I am executing 50K of these statements at a time.
Generally speaking, you're much better off inserting in bulk, provided you know that the inserts won't fail for some reason (i.e. invalid data, etc). If you're going row by row, what you're doing, is opening the data connection, adding the row, closing the data connection. Rinse wash, repeat in your case tens of thousa...
If you are using SSIS, I would suggest a data flow task as another possible avenue. This will allow you to move data from a flat text file, SQL table or other source and map it into your new table. Performance, I have found, is always pretty good and I use it regularly. If your table is not created before the insert, ...
Inserting rows - bulk or row by row?
[ "", "sql", "sql-server", "bulkinsert", "sql-insert", "" ]
Okay, That might be asked somewhere, but I am unable to find it over google or SO, My query was ``` INSERT INTO Tracking (OrderNum, PickupDate, ...) VALUES (95370,10/01/2013, .....) ``` plate form was a php script updating MS-Access db..and target column `pickupDate` was of Date/Time data type in access db.. when I...
When you use: ``` 10/01/2013 ``` it is an expression: 10 divided by 1 divided by 2013, giving as a result: `0,0049677`... which is then converted to a date, as dates are really numbers. When you use: ``` '10/01/2013' ``` It's a string, which is converted into a date. Internally, a date is stored as a number, not ...
My guess is that `10/01/2013` was interpreted as a division operation, so the resulting number was a small floating point number: ``` 0.00496770988 ``` From there, MySQL probably assumed you gave it a UNIX timestamp and it mangled the number to try to convert it into a storeable date. What you want to do instead is ...
What is Date? a string? or Double?
[ "", "mysql", "sql", "string", "date", "" ]
``` SELECT dealing_record.* ,shares.* ,transaction_type.* FROM shares INNER JOIN shares ON shares.share_ID = dealing_record.share_id INNER JOIN transaction_type ON transaction_type.transaction_type_id = dealing_record.transaction_type_id; ``` The above SQL code produces the desired output bu...
You have duplicate columns, because, you're asking to the SQL engine for columns that they will show you the same data (with `SELECT dealing_record.*` and so on) , and then duplicates. For example, the `transaction_type.transaction_type_id` column and the `dealing_record.transaction_type_id` column will have matching ...
Try to join shares with dealing\_record, not shares again: ``` select dealing_record.*, shares.*, transaction_type.* FROM shares inner join dealing_record on shares.share_ID = dealing_record.share_id inner join transaction_type on transaction_type.transaction_type_id= dealing_record.transacti...
Duplicate columns with inner Join
[ "", "sql", "sqlplus", "" ]
We are about to move our website to windows azure and faced a problem with sql-azure. They are not supporting the identity increment property due to a performance optimization. Hence we have to design our own logic to support the existing feature in generating sequential identity. So to generate unique sequential valu...
Use the following procedure to increment a value stored in a separate table. Putting an exclusive lock on the main table will result in horrible concurrency issues. ``` CREATE PROCEDURE [dbo].[GetNextID]( @IDName nvarchar(255) ) AS BEGIN /* Description: Increments and returns the LastID value from t...
You can achieve something similar this way 1. Start a transaction (in read committed transaction isolation level). 2. Select the max existing value with exclusive lock in `SELECT` query (`(XLOCK)` hint). 3. Update the value to be increased by 1. 4. Commit transaction. Putting exclusive lock into the select statement ...
SQL simulating Auto increment field
[ "", "sql", "sql-server", "transactions", "azure-sql-database", "" ]
I have this MySQL request: ``` SELECT * FROM candy RIGHT JOIN candytype ON candy.user_id = 1 AND candytype.candy_id = candy.id; ``` In my DB everything shows up but I see the same candy row showing twice because that one candy has two types. Is there a way that if it shows up once, that MySQL does not show it again...
I just needed to use DISTINCT. ``` SELECT DISTINCT candy.id, candy.name FROM candy RIGHT JOIN candytype ON candy.user_id = 1 AND candytype.candy_id = candy.id; ```
If you want just any old type, you can do this (here I'm guessing at column names): ``` SELECT candy.id, candy.name, min(candytype.type) FROM candy RIGHT JOIN candytype ON candy.user_id = 1 AND candytype.candy_id = candy.id GROUP BY candy.id; ``` If you want one row/candy, but you want to see all the types you can do...
How to remove repetitive rows in MySQL when using JOIN
[ "", "mysql", "sql", "" ]
i am trying to build a view that should look like this: ``` CREATE OR REPLACE VIEW TestView AS SELECT p.name, ?? (select count(*) from Test t where t.currentstate in ('Running', 'Ended') and t.ref = p.key) as HasValues from ParentTable p ``` I want the column HasValues to bei either 1 or 0. 1 if the count on the ...
If you potentially have a great many rows in the Test table for each row in the parenttable and the join key on the test table is indexed then it may be most efficient to construct the query as: ``` CREATE OR REPLACE VIEW TestView AS SELECT p.name, (select count(*) from Test t where t.currentstate in ...
``` CREATE OR REPLACE VIEW TestView AS SELECT p.name, case when nvl(t.mycount,0) > 0 then '1' else '0' end HasValues from ParentTable p left outer join (select ref, count(*) mycount from Test group by ref) t on t.ref = p.key ```
Oracle SQL View Column value 1 if count > n
[ "", "sql", "oracle", "" ]
I'm designing a database and I have a user table with users, and a group table with user's group. These groups will have a **owner** (a user that has created it), and a set of users that are part of the group (like a Whatsapp group). To represent this I have this design: ![enter image description here](https://i.sta...
If you don't add the `owner` in the `group` then where are you going to add it? The only way I see apart from this is adding a boolean `isowner` to the `usergroup`. Anyway, this would not make sense if there will only be 1 owner. If there can be `N` owners then that would be the way to go.
You are on the right track, but you'll need one more step to ensure an owner must actually belong to the group she owns: ![enter image description here](https://i.stack.imgur.com/ORoGm.png) There is a FOREIGN KEY in Group {groupID, owner} that references UserGroup {groupID, userID}. If your DBMS supports deferred fo...
Relationship redundant?
[ "", "sql", "database", "database-design", "" ]
I have some SQL code which generates random numbers using the following technique: ``` DECLARE @Random1 INT, @Random2 INT, @Random3 INT, @Random4 INT, @Random5 INT, @Random6 INT, @Upper INT, @Lower INT ---- This will create a random number between 1 and 49 SET @Lower = 1 ---- The lowest random number SET @Upper = 49; ...
I guess you could do something like this much simpler and much easier ``` DECLARE @Upper INT; DECLARE @Lower INT; SET @Lower = 1; /* -- The lowest random number */ SET @Upper = 49; /* -- The highest random number */ SELECT @Lower + CONVERT(INT, (@Upper-@Lower+1)*RAND()); ``` For getting a random numb...
For **Laravel**: ``` public function generatUniqueId() { $rand = rand(10000, 99999); $itemId = $rand; while (true) { if (!BookItem::whereBookItemId($itemId)->exists()) { break; } $itemId = rand(10000, 99999); } return $it...
Generate unique random numbers using SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I have a varchar collumn which may contain format like this: > 123,124,125,126 Now i want to get all number and put it in a single column like this in select command > 123 > 124 > 125 > 126 Any idea?
**Answering umpteenth time...** ``` WITH CTE AS (SELECT '123,124,125,126' AS COL1 FROM DUAL) SELECT REGEXP_SUBSTR ( COL1, '[^,]+', 1, RN ) COL1 FROM CTE CROSS JOIN (SELECT ...
Try this too, ``` with test as ( SELECT '123,124,125,126' str FROM dual ) SELECT regexp_substr (str, '[^,]+', 1, ROWNUM) SPLIT FROM TEST CONNECT BY LEVEL <= LENGTH (regexp_replace (str, '[^,]+')) + 1; ``` Try this if you have an additional comma at the end, ``` with test as ( SELECT '123,124,125,126,' s...
get numbers from string delimiter by ',' in oracle sql
[ "", "sql", "regex", "oracle", "" ]
I got the following tables: ``` pictures ------------------------------------ id name views votes ------------------------------------ id user_id pic_id ``` I want to get a result from a query that will give me each picture id, with the views of the picture, and the total votes from the table `votes` for the specifi...
You need to have `GROUP BY` clause. The use of `LEFT JOIN` will display all records on table `pictures` with or without matching record on table `votes`. ``` SELECT a.id, a.name, a.views, COUNT(b.pic_id) TotalVotes FROM pictures a LEFT JOIN votes b ON a.id = b.pic_id GROUP BY a.id, a...
Use left join with a group function ,normal join keyword means an inner join and you need a left join for one to many relation ``` SELECT `pictures`.`id`,`pictures`.`views`, COUNT(`votes`.`pic_id`) as votes FROM `pictures` LEFT JOIN `votes` ON `pictures`.`id` = `votes`.`pic_id` GROUP BY `pictures`.`id` ```
SQL query with count() from another table
[ "", "mysql", "sql", "" ]
I have a basic SQL question. To be able to explain it correctly.I'll give the schema of them . `Sailors(sid:integer,sname:string,rating:integer)` (sid is a primary key.) Now, the query is *"Find sailors whose rating is greater than some sailor called Horatio"* (there will be more than one Horatio since,sname is not a...
You couldn't use IN in with this subquery, because: 1. When you say `> ANY`, it returns those rows from outer query where the rating is higher than the rating of ANY of the ratings returned by the subquery. 2. If you would use `IN`, then it would return only those sailors who have the same rating as any of the sailor ...
I don't think you can use `in` for this, but you can use `exists`: ``` select * from Sailors S where exists ( select * from Sailors S2 where S2.sname = 'HORATIO' and S.rating > S2.Rating ) ```
SQL Set-Comparision Operators ANY and IN difference
[ "", "sql", "database", "predicate", "" ]
I have following two table Diagnose & Exercise I would like to extract Exercise date closest to the Diagnose\_Date and it should be 1 row from exercise table. I have tried left join with DATEDIFF function in where condition ``` SELECT D.ID,D.Diagnose_Date,D.Type1,D.Type2,E.Exercise_Date],E.Field1,E.Field2,E.Field3 FR...
First, in a CTE, for each diagnose get the smallest time interval between the diagnose date and all the exercise dates associated with that diagnose. ``` WITH MIN_DATES_CTE(ID, DATE_DIFF) AS ( SELECT ID, MIN(ABS(DATEDIFF(DAY,[Diagnose_Date],[Exercise_Date]))) FROM Exercise E INNER JOIN Diagnose D ON D.ID =...
I'm assuming you're just matching ANY single diagnose entry with ANY single exercise entry based on their dates being closest to each other. Here's my line of thinking: Do a full `JOIN` on diagnoses and exercises, order by absolute date difference, ascending. ``` SELECT D.ID, D.Date, E.ID, E.Date, ...
How to extract data from table2 which is closest to the DATE FIELD of table1?
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
data will be like this: ``` id | data ----|--------- 1 | AABBCC 2 | FFDD 3 | TTHHJJKKLL ``` what the result I want is ``` id | data ----|--------- 1 | AA 1 | BB 1 | CC 2 | FF 2 | DD 3 | TT 3 | HH 3 | JJ 3 | KK ...
1. Create function that parses incoming string (say "AABBCC") as a table of strings (in particular "AA", "BB", "CC"). 2. Select IDs from your table and use [CROSS APPLY](http://technet.microsoft.com/en-us/library/ms175156%28v=sql.105%29.aspx) the function with *data* as argument so you'll have as many rows as values co...
You Could do something like this ..... **Your Table** ``` CREATE TABLE TestTable ( ID INT, Data NVARCHAR(50) ) GO INSERT INTO TestTable VALUES (1,'AABBCC'), (2,'FFDD'), (3,'TTHHJJKKLL') GO SELECT * FROM TestTable ``` **My Suggestion** ``` CREATE TABLE #DestinationTable ( ID INT, Data NVARCHAR(50) ...
In SQL Server, how to create while loop in select
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I am getting a correct result, but now instead of showing me result that is 0 I want them to show me null result . How could I get results null instead of 0 ? ``` SELECT w.FIRST_NAME,w.LAST_NAME,COUNT(s.SECTION_ID) AS COUNTED_SECTIONS FROM INSTRUCTOR w LEFT OUTER JOIN SECTION s ON w.INSTRUCTOR_ID = s.INSTRUCTOR_ID GR...
I think `NULLIF()` is available in oracle: ``` SELECT w.FIRST_NAME,w.LAST_NAME,NULLIF(COUNT(s.SECTION_ID),0) AS COUNTED_SECTIONS FROM INSTRUCTOR w LEFT OUTER JOIN SECTION s ON w.INSTRUCTOR_ID = s.INSTRUCTOR_ID GROUP BY w.FIRST_NAME,w.LAST_NAME ORDER BY w.LAST_NAME; ```
Try nullif: ``` SELECT w.FIRST_NAME,w.LAST_NAME, NULLIF(COUNT(s.SECTION_ID), 0) AS COUNTED_SECTIONS FROM INSTRUCTOR w LEFT OUTER JOIN SECTION s ON w.INSTRUCTOR_ID = s.INSTRUCTOR_ID GROUP BY w.FIRST_NAME,w.LAST_NAME ORDER BY w.LAST_NAME; ```
how to display a row that is null instead of 0
[ "", "sql", "oracle", "null", "" ]
Could really use your help! I have a query: ``` Select * from Customers Where Customer_id in (001,002,003) ``` ...you get the idea. My problem is, if there is no record for customer\_id 003 for example, no record is displayed. How can i display "003" and state that no record was found? I would prefer this than havi...
Usually for this sort of thing I have a function which takes a csv and returns a table for me. Then I do something like the following. ``` -- this is creating the temporary table which would normally be created by a function. DECLARE @Temp TABLE (Customer_id int) INSERT INTO @Temp(Customer_id) SELECT 1 INSERT INTO @Te...
In SQL Server 2008+ you can use ``` SELECT V.Customer_id, C.* FROM (VALUES(1), (2), (3)) V(Customer_id) LEFT JOIN Customers C ON C.Customer_id = V.Customer_id ``` Non matching values will have `NULL` in the `C.Customer_id` column.
SQL where customer_id in (xx)
[ "", "sql", "sql-server", "sql-server-2012", "" ]
i have a job Name column in the JobDetails table.like this ``` job Name A_1 A_2 B_1 B_2 B_3 ``` I search max number like this ``` SELECT MAX(JobDetails.[Job Name]) FROM Monara.JobDetails WHERE ( [Job Name] like 'B_%' ) ``` Result is B\_3 But i want to get only 3. How can i do it?
I refuse to make a column containing space(s) Underscore is a wildchar that you should handle carefully when using *Like* ``` create table JobDetails ([JobName] varchar(10)) insert JobDetails values('A_1'),('A_2'),('B_1'),('B_2'),('B_3') SELECT max(cast(stuff(JobName, 1, patindex('%[_]%', JobName), '') as int)) FRO...
Try this code: ``` SELECT SUBSTRING(JobDetails.[Job Name], ( SELECT CHARINDEX('_', JobDetails.[Job Name]) ) + 1, LEN(JobDetails.[Job Name]) - CHARINDEX('_', JobDetails.[Job Name]) + 1) FROM Monara.JobDetails WHERE [Job Na...
How to get some value in column in sql server
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I'm using SQL developer, and my usual work is largely querying database tables with very long names.I don't have admin access to database, so I can't change the table names to short names.Plus it's a centralized database on which many people in many offices are working.To come to the point, I want to be able to have sh...
If you have enough privileges, you can create [synonyms](http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_7001.htm): ``` CREATE SYNONYM IAALN FOR somedb.I_am_a_long_name; ```
The simplest solution is to use synynoms (as suggested by @Smileek). If you can't or don't want to do that, you could create a view for every table you want to query: ``` CREATE VIEW IAALN AS SELECT * FROM I_am_a_long_name; ``` and use these views in your ad-hoc queries.
How to create a simple shortcut name for long table names?
[ "", "sql", "oracle", "oracle-sqldeveloper", "" ]
I am trying to make a php script to update a table column structure. ``` Name Type Collation Attributes Null Default promotion_dt date No 0000-00-00 ``` I want to update the structure to change Default to NULL, and seccond I want to replac...
One way would be to first alter the table to allow null, then change the default and last update the existing values that are equal to the default; ``` -- Set nullable and update the default ALTER TABLE myTable CHANGE promotion_dt promotion_dt DATE NULL DEFAULT NULL; -- Update the old values to the new default UPD...
``` ALTER TABLE tbl MODIFY promotin_dt DATE DEFUALT NULL; UPDATE tbl SET primotion_dt = NULL WHERE promotin_dt = '0000-00-00'; ```
SQL UPDATE TABLE COLUMN DEFAULT NULL QUERY
[ "", "mysql", "sql", "sql-server", "alter-table", "" ]
I need to fetch distinct values of a table, which has an auto-incremented id field. I need the id to identify, but I don't care which id when all values are the same except the id. I came up with the following, which seems to work. Is there a better way to do this though? ``` SELECT id, date_f, date_t, num_n, num_d, ...
If you're not using the id in the result set at all, then the answer above will do the job. If you need at least one Id in the result set for any purpose, then you should alter your statement slightly: ``` SELECT min(id), date_f, date_t, num_n, num_d, mn, is FROM t GROUP BY date_f, date_t, num_n, num_d, mn, is ``` w...
What you have is basically right - I would add that if you want the id (identity) then you need to add an aggregate such as - ``` SELECT min(id), date_f, date_t, num_n, num_d, mn, is FROM t GROUP BY date_f, date_t, num_n, num_d, mn, is ``` this will make sure that you get the first/same one each time (unless of cour...
Selecting distinct rows on all but one column
[ "", "mysql", "sql", "database", "" ]
How can I calculate the number of work days between two dates from table (from the 1st row to the end) in SQL Server 2008? I tried something like this, but it does not work ``` DECLARE @StartDate as DATETIME, @EndDate as DATETIME Select @StartDate = date2 from testtable ; select @EndDate = date1 from testtable ; SE...
I would always recommend a [Calendar table](http://blog.jontav.com/post/9380766884/calendar-tables-are-incredibly-useful-in-sql), then you can simply use: ``` SELECT COUNT(*) FROM dbo.CalendarTable WHERE IsWorkingDay = 1 AND [Date] > @StartDate AND [Date] <= @EndDate; ``` Since SQL has no knowledge of n...
This does it excluding the days out but date part rather than description. You can substitute the parameters used as an example for the values in your query. ``` Declare @startdate datetime = '2013-11-01', @enddate datetime = '2013-11-11' SELECT (DATEDIFF(dd, @StartDate, @EndDate) + 1) -(DATEDIFF(wk, ...
Calculating days to excluding weekends (Monday to Friday) in SQL Server
[ "", "sql", "sql-server-2008", "" ]
I have a stored procedure in which I am trying to execute a @cmd variable which is a BACKUP database command. When I run the stored procedure (which is in a job through the reporting agent) I get an error with the 'C:' in my path, I believe because the path is not encased in quotes. How can I encase the @Filename varia...
Change your query like ``` SET @cmd = 'BACKUP DATABASE ' + @DBName + ' TO DISK = ''' + @Filename + '''' ``` Also change all queries where @Filename variable used in your SP.
I think `REPLACE` + `QUOTENAME` makes the query much easier to read and maintain ``` SET @cmd = ' BACKUP DATABASE @DBName TO DISK = @Filename '; SET @cmd = REPLACE(@cmd, '@DBName', QUOTENAME(@DBName)); SET @cmd = REPLACE(@cmd, '@Filename', QUOTENAME(@Filename, '''')); ```
Adding Single Quotes Around A Scalar Variable
[ "", "sql", "sql-server", "" ]
Suppose I have a table named EMPLOYEE containing the following attributes ``` (EMPLOYEE_ID, LAST_NAME, FIRST_NAME, MIDDLE_NAME, JOB_ID, MANAGER_ID, Salary) ``` Can I Display the Nth highest salary drawing employee details Please help
**Test Table** ``` CREATE TABLE Test (ID INT IDENTITY(1,1), Salary INT) INSERT INTO Test VALUES (100), (200), (300), (400), (500) SELECT * FROM Test ``` **Query** ``` SELECT TOP 1 Salary FROM (SELECT TOP 3 Salary FROM Test ORDER BY Salary DESC)q ORDER BY Salary ASC ``` In your Sub-query SELECT TOP Nth the r...
`ORDER BY` and `LIMIT` where `10` is `n + 1`: ``` SELECT * FROM employees ORDER BY Salary DESC LIMIT 10, 1 ``` (If you want the first record, use `LIMIT 0, 1`. For the tenth, use `LIMIT 9, 1` etc.)
Mysql retriving the nth record
[ "", "mysql", "sql", "" ]
I am given a MySQL 12 digit TimeStamp (253402214400) to format it in `mm/dd/yyyy` without using any language. Database field is type of longtext and here is what I am doing. `SELECT time_stamp;` returns `253402214400` `SELECT DATE_FORMAT(time_stamp,'%m/%d/%Y');` returns `NULL` `SELECT FROM_UNIXTIME(time_stamp);` als...
I am sorry everybody, I think the time was givin in `milliseconds`, so by some research I could reach here <https://stackoverflow.com/a/9483289/750302> and resolved it with `DATE_FORMAT(FROM_UNIXTIME(time_stamp/1000), '%m/%d/%Y');` [SQLFIDDLE](http://sqlfiddle.com/#!2/93a575/2 "SqlFiddle")! ... > `Thank You Everyone f...
Try this: ``` DATE_FORMAT(FROM_UNIXTIME(time_stamp), '%d/%m/%Y') ``` Example: ``` SELECT DATE_FORMAT('2016-05-01 09:23:00', '%d/%m/%Y') // result: 01/05/2016 ```
Format MySQL timestamp to mm/dd/yyyy
[ "", "mysql", "sql", "timestamp", "unix-timestamp", "" ]
I have a table\_1: ``` id custno 1 1 2 2 3 3 ``` and a table\_2: ``` id custno qty descr 1 1 10 a 2 1 7 b 3 2 4 c 4 3 7 d 5 1 5 e 6 1 5 f ``` When I run this query to show the minimum order quantities from every customer: ``` SELECT DISTINC...
"Generic" SQL way: ``` SELECT table_1.custno,table_2.qty,table_2.descr FROM table_1, table_2 WHERE table_2.id = (SELECT TOP 1 id FROM table_2 WHERE custno = table_1.custno ORDER BY qty ) ``` SQL 2008 way (probably faster): ``` SELECT custno, qty, descr...
First of all... I'm not sure why you need to include `table_1` in the queries to begin with: ``` select custno, min(qty) as min_qty from table_2 group by custno; ``` But just in case there is other information that you need that wasn't included in the question: ``` select table_1.custno, ifnull(min(qty),0) a...
left join without duplicate values using MIN()
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "join", "" ]
Suppose i have a long query string for eg. ``` SELECT id from users where collegeid='1' or collegeid='2' . . . collegeid='1000' ``` will it affect the speed or output in any way? ``` SELECT m.id,m.message,m.postby,m.tstamp,m.type,m.category,u.name,u.img from messages m join users u on m.postby=u.uid where m.cid =...
I would prefer to use `IN` in this case as it would be better. However to check the performance you may try to look at the Execution Plan of the query which you are executing. You will get the idea about what performance difference you will get by using the both. Something like this: ``` SELECT id from users where co...
Obviously, there is no direct correlation between the length of a query string and its processing time (as some very short query can be tremendeously complex and vice versa). For your specific example: It depends on how the query is processed. This is something you can check by looking at the query execution plan (synt...
Does long query string affect the speed?
[ "", "mysql", "sql", "performance", "optimization", "" ]
I have the following table ``` col1 col2 col3 col4 ==== ==== ==== ==== 1233 4566 ABCD CDEF 1233 4566 ACD1 CDEF 1233 4566 D1AF CDEF ``` I need to count the characters in col3, so from the data in the previous table it would be: ``` char count ==== ===== A 3 B 1 C 2 D ...
Knowing that colum3 has a fixed length of 4, this problem is quite easy. Assume there is a view V with four columns, each for one character in column 3. ``` V(c1, c2, c3, c4) ``` Unfortunately, I'm not familiar with Access-specific SQL, but this is the general SQL statement you would need: ``` SELECT c, COUNT(*) FR...
You can accomplish your task in pure Access SQL by using a Numbers table. In this case, the Numbers table must contain integer values from 1 to some number larger than the longest string of characters in your source data. In this example, the strings of characters to be processed are in [CharacterData]: ``` CharacterL...
Counting characters in an Access database column using SQL
[ "", "sql", "ms-access", "vba", "" ]
How can I display data from table1 where its id (Table1 Id)is not contained in table2 ``` string Query = "SELECT * FROM Table1 WHERE Table1ID!=" Table2_Table1ID; ```
``` SELECT * FROM TABLE1 WHERE NOT EXISTS(SELECT Table1ID from Table2 where Table1ID=Table1.Id) ```
You can do: ``` SELECT * FROM table1 WHERE table1ID NOT IN (SELECT table1ID FROM table2); ```
display data from table1 where its id (Table1 Id)is not contained in table2
[ "", "sql", "" ]
We had an issue with our stock whereby we had a balance column that would be added to or subtracted from whenever a transaction occurred. There were some issues that we could not trace and hence have made changes whereby the stock would be calculated by adding and subtracting (where appropriate) the quantity moving and...
try to include all product-ids and group by it. here's some proposed code ``` select prodid, sum(total) as total from ( (select s.prodid , ISNULL(sum(gd.qty),0) as total from grns as g INNER JOIN grndetails as gd ON g.id = gd.grnid INNER JOIN ...
Try this: ``` WITH S AS ( SELECT DISTINCT prodid FROM stocks ), L AS ( /* SELECT 10 AS locationid */ SELECT DISTINCT locationid FROM grns ), T1 AS ( select g.locationid, s.prodid, sum(gd.qty) as grnadd from grns as g ...
Calculating stock quantity from multiple table transactions with SQL
[ "", "sql", "sql-server", "" ]
suppose i have this table: ``` group_id | image | image_id | ----------------------------- 23 blob 1 23 blob 2 23 blob 3 21 blob 4 21 blob 5 25 blob 6 25 blob 7 ``` how to get results of only 1 of each group id? in this case,th...
There are **no** standard aggregate functions in Oracle that would work with `BLOB`s, so `GROUP BY` solutions won't work. Try this one based on `ROW_NUMBER()` in a sub-query. ``` SELECT inn.group_id, inn.image, inn.image_id FROM ( SELECT t.group_id, t.image, t.image_id, ROW_NUMBER() OVER (PARTITION BY t....
``` SELECT group_id, image, image_id FROM a_table WHERE (group_id, image_id) IN ( SELECT group_id, MIN(image_id) FROM a_table GROUP BY group_id ) ; ```
How to get only one record for each duplicate rows of the id in oracle?
[ "", "sql", "oracle", "greatest-n-per-group", "" ]
I have MyTable with a Column Message NVARCHAR(MAX). Record with ID 1 contains the Message '0123456789333444 Test' When I run the following query ``` DECLARE @Keyword NVARCHAR(100) SET @Keyword = '0123456789000001*' SELECT * FROM MyTable WHERE CONTAINS(Message, @Keyword) ``` Record ID 1 is showing up in the result...
Found a solution that works. I've added `language 1033` as an additional parameter. ``` SELECT * FROM MyTable WHERE CONTAINS(Message, @Keyword, langauge 1033) ```
This is because the @Keyword is not wrapped in double quotes. Which forces zero, one, or more matches. > Specifies a match of words or phrases beginning with > the specified text. Enclose a prefix term in double quotation marks > ("") and add an asterisk (*) before the ending quotation mark, so that > all text startin...
Strange behaviour with Fulltext search in SQL Server
[ "", "sql", "sql-server", "t-sql", "full-text-search", "contains", "" ]
I have a table looks like given below query, I add products price in this table daily, with different sellers name : ``` create table Product_Price ( id int, dt date, SellerName varchar(20), Product varchar(10), Price money ) insert into Product_Price values (1, '2012-01-16',...
I think this is what you're looking for. [SQLFiddle](http://sqlfiddle.com/#!3/e4bb4/3) It's kind of ugly, but here's a little breakdown. This block allows you to get a dynamic list of your values. (Can't remember who I stole this from, but it's awesome. Without this, pivot really isn't any better than a big giant ca...
The problem is this requirement: > I want result like this for n number of sellers If you have a fixed, known number of columns for your results, there are several techniques to [PIVOT](http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx) your data. But if the number of columns is not known, you'r...
Product price comparison in sql
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have table which list a number of cases and assigned primary and secondary technicians. What I am trying to accomplish is to aggregate the number of cases a technician has worked as a primary and secondary tech. Should look something like this... ``` Technician Primary Secondary John 4 ...
You can group two subqueries together with a FULL JOIN as demonstrated in this [SQLFiddle](http://www.sqlfiddle.com/#!6/0db6a/1). ``` SELECT Technician = COALESCE(pri.Technician, sec.Technician) , PrimaryTech , SecondaryTech FROM (SELECT Technician = PrimaryTech , PrimaryTech = COUNT(*) FROM C...
``` Select Tech, sum(case when IsPrimary = 1 then 1 else 0 end) as PrimaryCount, sum(case when IsPrimary = 0 then 1 else 0 end) as SecondaryCount from ( SELECT SecondaryTech as Tech, 0 as IsPrimary FROM your_table union all SELECT PrimaryTech as Tech, 1 as IsPrimary FROM your_table ) x GROUP BY...
SQL Aggreate Functions
[ "", "sql", "sql-server", "sql-server-2008", "aggregate", "" ]
I have come across many websites to find the answer about which one is better, ANSI or non- ANSI syntax. What is the difference between these two queries? ``` select a.name,a.empno,b.loc from tab a, tab b where a.deptno=b.deptno(+); ``` and: ``` select a.name,a.empno,b.loc from tab a left outer join tab b on a.dept...
both syntaxes usually work without problems, but if you try to add a where condition you will see that with the second one is much simpler to understand which is the join condition and which is the where clause. 1) ``` SELECT a.name, a.empno, b.loc FROM tab a, tab b WHERE a.deptn...
The first is a legacy Oracle specific way of writing joins, the second is ANSI SQL-92+ standard and is the preferred one.
What is difference between ANSI and non-ANSI joins, and which do you recommend?
[ "", "sql", "oracle", "join", "" ]
have table with some values ``` role_number action_number status 4 2 1 4 5 0 4 8 1 4 7 0 4 10 1 4 3 0 ``` Now want new role\_number with same actio...
``` INSERT INTO YourTable (role_number, action_number, status) SELECT role_number + 1, action_number, status FROM YourTable WHERE role_number = 4 ```
Here it is a possible solution using INSERT/SELECT: ``` INSERT INTO YourTable(role_number, action_number, status) SELECT @NewRoleNumber, action_number, status FROM YourTable WHERE RoleNumber = @RoleNumberToBeCopied ```
How to copy values from table for another column
[ "", "sql", "sql-server", "" ]
I am trying to get this table to display book num, book title, and the number of times each book was checked out (even if it was never checked out.) The current output I get is correct, but I want to sort it by book num and "Times Checked Out". ``` SELECT book.book_num ,book_title ,Count(checkout.book_num) AS "Ti...
You can also use it as inner query: ``` SELECT * FROM ( SELECT book.book_num,book_title,Count(checkout.book_num) AS "Times Checked Out" FROM checkout right join book ON checkout.book_num = book.book_num GROUP BY book.book_num, book_title ) AS foo ORDER BY "Times Checked Out"; ```
``` SELECT book.book_num, book_title, COUNT(checkout.book_num) AS "Times Checked Out" FROM checkout RIGHT JOIN book ON checkout.book_num = book.book_num GROUP BY book.book_num, book_title ORDER BY book.book_num, COUNT(checkout.book_num); ```
Need help sorting table with an aggregate function
[ "", "sql", "" ]
I am using SQL Server 2008 and I have two separate Count queries. I want to divide the two queries and multiply by 100 to get a percentage. The two Queries ``` SELECT COUNT(*) FROM ( SELECT * FROM admin WHERE principal LIKE '%Mrs%' UNION SELECT * FROM admin where deputy_principal LIKE '%Mrs%' ) as Cou...
``` SELECT ((SELECT CAST(COUNT(*) AS DECIMAL(18,2)) FROM admin WHERE principal LIKE '%Mrs%' OR deputy_principal LIKE '%Mrs%') / (SELECT CAST(COUNT(*) * 2 AS DECIMAL(18,2)) FROM admin)) * 100 ``` **UDPATE: Comparison vs original approach with dummy data....** ``` DECLARE @admin TABLE(Id INTEGER IDEN...
You could try something like below using `CASE Expression` and `SUM() Function`: ``` SELECT SUM(CASE WHEN principal LIKE '%Mrs%' OR deputy_principal LIKE '%Mrs%' THEN 100.0 END) / SUM(2) Pecentage FROM admin ``` **[Fiddle demo](http://sqlfiddle.com/#!3/d132d/18)** using @AdaTheDev 's data
Add two different SQL Count Queries
[ "", "sql", "sql-server", "" ]
I need to use sql query using VBA. My input values for the query is from the Column in the excel sheet.I need to take all the values present in the column and it should be passed as input to the query to sqlserver. But i could'nt get the answer. I am getting type mismatch as error. could any one help me out. Thanks in ...
change to ``` stSQL = stSQL + " ('" + Replace(wsSheet.range("J:J").Value, "'", "") + ")" ``` but sql IN statement is usually used like this ``` state IN (25,26,28) ``` But if you are only using one integer value you might want to go this way. ``` stSQL = "SELECT * FROM prod..status where state = " stSQL = Val(wsSh...
I used for loop and mid command to convert the values in the column to a single variable. Below is the code i used to perform the function which i required ``` ' Getting the last row With wsSheet lastrow1 = .Range("J" & .Rows.Count).End(xlUp).Row End With ' Appending the values to a single variable For i = 1 To last...
Sql query taking values from the column in the excelsheet using VBA(macro)
[ "", "sql", "vba", "" ]
given this Schema: ``` table tblSET SetID int PK SetName nvarchar(100) Table tblSetItem SetID int PK ItemID int PK ``` tblSetItem.SetID is a FK into the tblSet Table. Some data: **tblSet** ``` SetID SetName 1 Red 2 Blue 3 Maroon 4 Yellow 5 Sky ``...
You can use xml support to create a comma separated list (cf this answer: <https://stackoverflow.com/a/1785923/215752>). For this case I don't care about the form so I leave the starting comma in. Note, I couldn't test this right now so I might have a typo... ``` select * from ( select SetID, setitemuniquestring, ...
I do assume that you need to identify sets which contents is exactly the same. So i would go for a temp table, where to store an "hash" of the contained item. Hash may be as simple as a list of item ids comma separated. Eg. ``` Set Hash 1 100,101 2 100,108,109 3 100,101 4 101,108,109,110 5 100,108,109 ``` ...
SQL Find duplicate sets
[ "", "sql", "sql-server-2008-r2", "" ]
The image shows my proposed layout for part of a database. My concern is with the price bands and the way these attach to [shows] and [bookings]. There needs to be a list of price bands (as in titles) but the same band can have multiple values depending on which show it is attached to (a standard ticket for Friday coul...
I think that your approach is correct. You have * different ticket types * different shows And their relation is n:n. The correct solution for resolving a n:n relation is a separate table (in your case ShowPriceBand) to enlist all the combinations.
As the relationship between `Show` and `PriceBand` is many-to-many, it is a standard approach to define an intermediary table to define this relationship. In your case, apart from the linking columns (foreign keys to `Show` and `PriceBand`) you defined additional properties of the link. This is a valid approach and th...
Database layout/design inefficient
[ "", "sql", "sql-server", "database", "database-design", "" ]
I am using Spring Framwork, `SimpleJdbcTemplate`, to call a stored procedure (SQL-Server) from my Java code. For the stored procedures that do some update/insert, I do call `simpleJdbcTemplate.update(...)` and for the ones with select only, I call `simpleJdbcTemplate.query(...)`. Both works fine. Now, I have a stored...
So long as the SQL Server sproc actually works without error and returns data, it should be of no consequence that it might also perform an update as well (I'd make sure that the sproc did its update first and ended with the select). If this is the case then simpleJdbcTemplate.query(...) should do the trick. I don't kn...
In case your SQL executed by a `Statement` or any of its subclasses (viz. `PreparedStatement`, `CallableStatement`) has multiple SQL statements inside it (can be INSERT/UPDATE/DELETE/SELECT), you should use the `execute()` method on the statement to execute such SQL, then call [getMoreResults](http://docs.oracle.com/ja...
Call a stored procedure that do both select and update
[ "", "sql", "sql-server", "spring", "stored-procedures", "spring-jdbc", "" ]
I have been using the following SQL: ``` SELECT DISTINCT NAME FROM Events t1 LEFT JOIN UserHistory t2 ON t1.Name = t2.Event WHERE t2.Event IS NULL ``` To select all rows from table 1 where table 2 is Null. This effectively filters out all my Table 1 data where Table 2 has data. However, I want to apply this only when...
``` SELECT DISTINCT NAME FROM Events t1 LEFT JOIN UserHistory t2 ON t1.Name = t2.Event and t2.certain_column = 1234 WHERE t2.Event IS NULL ```
Also you can try query with NOT EXISTS: ``` SELECT DISTINCT NAME FROM Events t1 WHERE NOT EXISTS(SELECT * FROM UserHistory t2 WHERE t1.Name = t2.Event AND t2.ID = 1) ```
SQL Select where NOT matching specific selection
[ "", "mysql", "sql", "" ]
How to get all column names without one column in sql table in SQL Server. I have a temp table. It has columns: ``` ID, Status, Code, Name, Location, Address, Title, Category, Line, date, time, UserName ``` I want all data without the `id` column I want an alternative to this SQL code for this ``` SELECT Status, C...
Please try below query to select all column data without a column. Variable `@ColList` gives the column names except column `ID`: ``` DECLARE @ColList nvarchar(4000), @SQLStatment nvarchar(4000),@myval nvarchar(30) SET @ColList = '' select @ColList = @ColList + Name + ' , ' from syscolumns where id = object_id('Table...
Unfortunately there is no "SELECT Everything except some columns" in SQL. You have to list out the ones you need. If this is a temp table I guess you could try to drop the ID column before selecting the result. This is not appropriate if you need it again though... ``` ALTER TABLE Temp DROP COLUMN Id Then SELECT * ...
How to get all column names without one column in sql table in SQL Server
[ "", "sql", "sql-server", "database", "" ]
Suppose I have a table ``` id value ------ --------- A 123 A 422 B 441 B 986 B 674 C 648 ``` I need a query which will return only those id's which have 3 or more values associated with them. So, in that case...
Use the `Group By` clause with [`Having`](http://technet.microsoft.com/en-us/library/ms180199.aspx): ``` SELECT id FROM dbo.TableName GROUP BY ID HAVING COUNT(*) >= 3 ``` `Demo`
In case you want to include the value, you can use window functions to find the ones with three or more rows, e.g.: ``` DECLARE @x TABLE(id CHAR(1), value INT); INSERT @x SELECT 'A', 123; INSERT @x SELECT 'A', 422; INSERT @x SELECT 'B', 441; INSERT @x SELECT 'B', 986; INSERT @x SELECT 'B', ...
Only return rows where the value appears more than n times
[ "", "sql", "sql-server", "count", "" ]
In my table I have `myDate` column of type `nvarchar(50)`. The result I need is to select this date/time: `07/11/2013 11:22:07` And I need to get `07/11/2013 11:22:07 am` from it (add `am/pm` to the original date&time). I tried everything but get only the original data without am/pm. This is an example from my quer...
`try this !!` ``` declare @date datetime set @date='07/11/2013 11:22:07' SELECT cast(convert(varchar(20),substring(convert(nvarchar(20),@date, 9), 0, 21) + ' ' + substring(convert(nvarchar(30), @date, 9), 25, 2),105) as datetime) ```
You can get AM/PM data using following query ``` declare @date datetime select @date= CAST('07/11/2013 11:22:07' AS datetime) select RIGHT ( CONVERT(VARCHAR,@date,9),2) ```
Convert from nvarchar to DateTime with am pm?
[ "", "sql", "sql-server", "datetime", "type-conversion", "" ]
I have a Table called "contas" and another table called "cartoes" I need to verify what "IDCARTAO" doesn't exists in table contas, like that: "If I have one conta with cartoes.IDCARTAO = 1, the result needs to be 2 and 3"; ``` SELECT cartoes.IDCARTAO from cartoes WHERE NOT EXISTS(SELECT * from cartoe...
Are you looking for this? ``` SELECT IDCARTAO FROM cartoes c WHERE NOT EXISTS ( SELECT * FROM contas WHERE IDCARTAO = c.IDCARTAO ) ```
Tiny tweak: Instead of using `not exists`, try `not in`. As in... ``` SELECT ct.IDCARTAO from cartoes ct WHERE ct.idcartao not in (SELECT c.idcartao from contas c) ```
NOT EXISTS Clause
[ "", "mysql", "sql", "" ]
I have a basic database with a few columns i will show u below I have a program that allows the user to input if they are Male OR Female OR NULL if they want to Then they must select a Category such as Love OR Cooking I tried this Query but it didnt work It displayed other Genders ignoring the Where Gender = M state...
You need to add brackets around the OR Something like ``` SELECT * FROM products WHERE Gender = "M" AND (Category = "Love" OR Category = "Cooking") ``` The way you have it, it would be the same as ``` SELECT * FROM products WHERE (Gender = "M" AND Category = "Love") OR Category = "Cooking" ``` Have a look at [Op...
You have to wrap the categories in brackets in order to tell the query that the gender has to be "M" : ``` SELECT * FROM products WHERE Gender = "M" AND (Category = "Love" OR Category = "Cooking") ```
Trouble getting SQL query to work
[ "", "mysql", "sql", "database", "" ]
I'm using SQL Server 2008 R2. I have table called EmployeeHistory with the following structure and sample data: ``` EmployeeID Date DepartmentID SupervisorID 10001 20130101 001 10009 10001 20130909 001 10019 10001 20131201 002 10018 10001 20140501 002 10...
A bit involved. Easiest would be to refer to [this SQL Fiddle](http://sqlfiddle.com/#!6/8879fb/4) I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives. The gist is, you get a can...
I would do something like this: ``` ;WITH x AS (SELECT *, Row_number() OVER( partition BY employeeid ORDER BY datestart) rn FROM employeehistory) SELECT * FROM x x1 LEFT OUTER JOIN x x2 ON x1.rn = x2.rn + 1 ``` Or maybe i...
Trouble using ROW_NUMBER() OVER (PARTITION BY ...)
[ "", "sql", "sql-server", "sql-server-2008", "row-number", "gaps-and-islands", "" ]
I am a newbie and i am using **mysql**. I want to create a table **product** from an existing table **customer** but i want only the selected columns of **customer** table to be created in new table and that too with the same structure. Eg In customer table there is a column with name **DATE** which has **default as CU...
Here is what you can do 1. use [`CREATE TABLE new_table LIKE old_table`](http://dev.mysql.com/doc/refman/5.5/en/create-table.html) syntax to create a new table with the same structure 2. use [`ALTER TABLE new_table DROP COLUMN unnecessary_column`](http://dev.mysql.com/doc/refman/5.5/en/alter-table.html) syntax to drop...
USE THIS ``` CREATE TABLE NEW-TAB SELECT NAME,DATE FROM OLD-TAB; ``` Please change COLUMN/TABLE names as per your requirements
Create a table in Mysql from selected columns of exisiting table and with same structure
[ "", "mysql", "sql", "" ]
I need to figure out how to find a certain group of records using T-SQL and I'm having trouble figuring out how I would need to create the `WHERE` clause to do this. I have a SQL 2008 R2 system that I'm working with, and in this database there are a couple of tables. One contains personnel records, and another contain...
Try this, it should get all Personnel rows with no matching primary address: ``` SELECT * FROM Personnel p WHERE NOT EXISTS (SELECT * FROM Address a WHERE a.personnelId = p.id AND a.isprimary = 1) ```
This ends up beeing a [Left anti semi join](http://sqlity.net/en/1360/a-join-a-day-the-left-anti-semi-join/) pattern and can be written like this: ``` SELECT id, name FROM personnel p LEFT OUTER JOIN address a ON p.id = a.personnelid AND a.isprimary = 1 WHERE a.personnelId IS NULL ``` It can be interesting to...
One to many relationships in T-SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I am trying to get the latest `PatientData.DateVal` and `PatientData.DecVal` before `PatientTreatment.Startdate` for each row in `PatientTreatment`. E.g I want the latest date and value for a specific type of patientdata before each treatment for every patient. I have used the script below. It works OK. But this scrip...
You can use window functions to do this: ``` select x.PatentId, x.StartDate, x.DateVal, x.DecVal from ( select t.PatientId, t.StartDate, p.DateVal, p.DecVal, row_number() over ( partition by t.patientid, t.StartDate order by p.DateVal ...
Similar to the windowed example above but with a CTE: ``` ;WITH OrderedPatientData AS ( SELECT PatientID, StartDate, DateVal AS LastDateValBeforeStartdate, DecVal AS LastDecValBeforeStartdata, ROW_NUMBER() OVER (Partition BY PatientID ORDER BY DateVal DESC) RowNum ...
SQL Server get latest value in table x before date for not distinct rows in table y
[ "", "sql", "sql-server", "max", "row-number", "" ]
I need to count the number of duplicates in a column, which works when done like this: ``` SELECT CorrelationId, Count(CorrelationId) as total FROM VoipDetailsView WHERE ResponseCode = 200 GROUP BY CorrelationId ``` However, when I try to add other columns to the result ``` SELECT SessionIdTime, CorrelationId, Count...
You need to separate the aggregation of CorrelationId into a separate query and join that with your table to fetch other columns, something like: ``` SELECT v.SessionIdTime, v.CorrelationId, total From VoipDetailsView v inner join (SELECT CorrelationId, Count(CorrelationId) as total FROM VoipDetailsView WHERE Response...
How about using an aggregate function on the `SessionIdTime` column like `min()` ``` SELECT min(SessionIdTime), CorrelationId, Count(CorrelationId) as total FROM VoipDetailsView WHERE ResponseCode = 200 GROUP BY CorrelationId ORDER BY min(SessionIdTime) ```
Adding column to group by clause messes up counting
[ "", "sql", "sql-server", "" ]
As u expect I have got problem with GETDATE in DEFAULT constraint on some tables in SQL Server 2012. I have got two tables like below (A and B): ``` CREATE TABLE [dbo].[TABLE_A_OR_B] ( [TABLE_A_OR_B_PK] BIGINT IDENTITY (1, 1) NOT NULL, [CREATE_DATETIME] DATETIME2 (7) CONSTRAINT [DF_TABLE_A_OR_B_CREATE_...
GETDATE to SYSDATETIME change in constraints seems to solve problem.
[`GETDATE()`](http://technet.microsoft.com/en-us/library/ms188383.aspx) is derived from the operating system's clock - if something caused the clock on the server to change (to an earlier time), you'll achieve your (apparent) time travel. What could cause such changes? The obvious are a manual adjustment, or if the se...
GETDATE in DEFAULT constraint on some tables in SQL Server 2012
[ "", "sql", "sql-server", "constraints", "getdate", "" ]
Is it possible to use array as source for merge statement E.g. I have the below merge statement and when I compile, I am getting error. How can I use merge with array as source table? ``` PLS-00436: implementation restriction: cannot reference fields of BULK In-BIND table of records ``` Procedure code ``` CREATE o...
There is a restriction in Oracle 10g - you can't access individual fields of records in `FORALL` statement. You could do it if you were using Oracle 11g. There are workarounds, however, and I recommend the following article that proposes a few of them: [PLS-00436 in 10g - Workaround](http://www.oracle-developer.net/di...
The problem here is that you are referring to the same collection in your `SET` clause and `WHERE` clause. See [Oracle Documentation for Forall statement](http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/forall_statement.htm), go to the Restrictions section, second bullet point. I would suggest you rename your `v...
Merge statement array as source table
[ "", "sql", "oracle", "plsql", "merge", "oracle10g", "" ]
Tables: ``` Country ------- PK CountryID Name City ------- PK CityID FK CountryID Name Airport -------- PK AirportID FK CityID Name ``` My task is to select names of countries that have no airport. I can imagine only one solution with EXCEPT (or MINUS) ``` SELECT Country.Name FROM Country EXCEPT (SELECT DIS...
If you need to make this query with `IS NULL` try following query: [SQLFiddle demo](http://sqlfiddle.com/#!2/c56dc/4) ``` select ct.CountryId,max(ct.Name) from Country ct left join City c on ct.CountryId=c.CountryId left join Airport a on a.CityId=c.CityID group by ct.CountryId HAVING max(a.AirportID) IS NULL ```
``` SELECT cn.CountryID FROM Country cn LEFT JOIN City ct ON cn.CountryID = ct.CountryID LEFT JOIN Airport ar on ar.CityID=ct.CityID WHERE ar.AirportID is null ```
SQL query - IS NULL
[ "", "sql", "" ]
I have the following queries 1. DELETE FROM A WHERE Id IN (SELECT Id FROM B) 2. DELETE FROM B I want to make sure that the first statement is complete before the second is executed since the 1) is dependent on 2) I want to know if I execute these queries just like this, does SQL take care of completing the first tra...
You can execute queries in succession by separating them with a semicolon `;`. More details are in the [MySQL documentation](https://dev.mysql.com/doc/refman/5.0/en/entering-queries.html). Simply do: ``` DELETE FROM A WHERE Id IN (SELECT Id FROM B); DELETE FROM B; ``` Based on your requirement; this does exactly wha...
If the statements are in the same batch it's guaranteed. But you might want to wrap them in a transaction to ensure that either both happen or neither happen (get rolled back).
How to execute two DELETE queries one after another
[ "", "mysql", "sql", "" ]
I am new to databases and i really stuck! Please give me a hand! Have no idea, where I made a mistake... I have 2 tables patient and caretaker they both have lastname and firstname I need to retrieve lastname and firstname from both of them and i made the following query: SELECT firstname FROM `mortenu8`.`patient`,...
Use Database Objects. When you specify the firstname in the columns list where both the tables have the same column name, data base engine cannot recognize the first name of which table exactly are you trying to retrieve!! Many of the above answers says the same thing. Just to reiterate the same, ``` SELECT patient...
Assuming your query of join is working you can try this ``` SELECT patient.firstname,caretaker.firstname FROM mortenu8.patient, caretaker where caretaker.firstname = patient.firstname ``` OR ``` SELECT caretaker.firstname FROM mortenu8.patient, caretaker where caretaker.firstname = patient.firstname ```
Retrieving names from 2 tables with same column names
[ "", "mysql", "sql", "" ]
I recently set up a MYSQL database connected to a form filled with checkboxes. If the checkbox was selected, it would insert into the associated column a value of '1'; otherwise, it would receive a value of '0'. I'd like to eventually look at aggregate data from this form, and was wondering if there was any way I coul...
If you are just looking for the sheer number of 1's in the columns, you could try… ``` select sum(col1), sum(col2), sum(col3) from POLLDATA ```
``` SELECT SUM(CASE WHEN t.your_column = '1' THEN 1 ELSE 0 END) AS OneCount, SUM(CASE WHEN t.your_column='0' THEN 1 ELSE 0 END) AS ZeroCount FROM YOUR_TABLE t ```
MYSQL get count of each column where it equals a specific value
[ "", "mysql", "sql", "count", "" ]
I wrote a SELECT query to find out how many records will be impacted with my UPDATE query. The SELECT and UPDATE returned different record counts. Here is my SELECT query: ``` SELECT * FROM T1 JOIN T2 on T1.ID = T2.ID WHERE T1.Name IS NULL AND T2.Status = 'happy' ``` Here is my UPDATE query: ``` UPDATE T1 SET T1...
That can happen on a one to many join when you're updating the one side. In your case, it looks like there are more than one `T2` row for some of your `T1` rows, and the server will return the `T1` row as many times as there is matches in the `T2` table. Check if this matches your update count: ``` SELECT count(disti...
One possible reason: You have instances of `ID` where more than one `T2` record exists for the corresponding `T1` record
Why SELECT and UPDATE Return Different Record Counts/Affected
[ "", "sql", "sql-update", "" ]
In Excel I make an Analysis Services connection to a data cube. I would like to be able to show a user how current the data is by showing them when the last cube processing time occurred. Making an analysis services connection to the cube in SQL Server Management Studio (SSMS), I can right click on the cube and see the...
I actually found a way to do it in Excel without having to create any views or new measures. In Excel 2013, **PowerPivot** allows you to create your own custom MDX queries against a cube. You can open PowerPivot, make the connection to your cube, paste in the MDX query I used in SSMS to return the cube process time, `...
I had the same need on a project, to show cube last processed date/time in Excel. This may be a little hokie but it definitely works. I added a query against my database in my DSV (technically I made a view since all of my source data came from views rather than named queries or tables) that was just ``` Select CURREN...
Get SSAS cube last process time
[ "", "sql", "excel", "vba", "ssas", "olap-cube", "" ]
I'm trying to figure out how to determine the total sales for an employee using MySQL. The DB has 4 tables in it that will help determine the total sales. I was able to create a Query that selects all the necessary tables to calculate the Sales Total. Query: ``` SELECT employees.eno, employees.ename, orders.ono, orde...
Try: ``` SELECT employees.eno, employees.ename, SUM(parts.price * odetails.qty) as TotalSales FROM test.employees INNER JOIN test.orders ON empoyee.eno = orders.eno INNER JOIN test.odetails ON orders.ono = odetails.ono INNER JOIN test.parts ON odetails.pno = parts.pno GROUP BY employees.eno, employees.ename ```
The following *should* work. ``` SELECT employees.ename, COUNT(employees.ename), (COUNT(employees.ename) * parts.price) FROM test.employees INNER JOIN (orders, parts) ON (employees.eno = orders.eno AND parts.pno = odetails.pno) ```
Calculating Total Sales from Multiple MySQL Tables
[ "", "mysql", "sql", "" ]
I have a table with dates that all happened in the month November. I wrote this query ``` select id,numbers_from,created_date,amount_numbers,SMS_text from Test_Table where created_date <= '2013-04-12' ``` This query should return everything that happened in month 11 (November) because it happened **before** the dat...
Instead of '2013-04-12' whose meaning depends on the local culture, use '20130412' which is recognized as the culture invariant format. If you want to compare with December 4th, you should write '20131204'. If you want to compare with April 12th, you should write '20130412'. The article [Write International Transact-...
Try like this ``` select id,numbers_from,created_date,amount_numbers,SMS_text from Test_Table where created_date <= '2013-12-04' ```
Query comparing dates in SQL
[ "", "sql", "sql-server", "date", "compare", "" ]
i have select statment query with join statment, which I use to get value from joining the table here's my Select query: ``` select case when p1.Value2 is not null then p1.Value3 end as fix1, case when p1.Value2 is not null then p2.Value3 end as fix2, case when p1.Value2 is not null then p3.Value3 end as fix3, case ...
How about such solution? ``` SELECT /*extra fields from tc ==>>*/ x, y /*<<==*/ , FIX, FIX1, FIX2, FIX3, FIX4, FIX5 FROM ( SELECT fields, P.Value3, /*extra fields from tc ==>>*/ x, y /*<<==*/ FROM ( SELECT * FROM tc WHERE CUST_ACCT ='10053996' ) T UNPIVOT ( unpvt FOR...
You can replace `Case` Statement with `IsNull(expression, valueIfNull)` in your first statement. i have select statment query with join statment, which I use to get value from joining the table here's my Select query: ``` select IsNull(p1.Value2 ,p1.Value3) as fix1, IsNull(p1.Value2 ,p1.Value3) as fix2, IsNull(p1.V...
Simplify Multiple Join SQL Column
[ "", "sql", "sql-server", "join", "" ]
I have three dates in table, for each record i need to find out max of three columns and need to ignore incase if the column is null, could you please help on this ? I am using oracle 10g version. ``` Table-1 --------- SL NO date1 date2 date3 age ```
Since `GREATEST` will return `NULL` if any of the values that you pass it is `NULL`, you need a combination of `GREATEST` and `COALESCE`: ``` SELECT GREATEST( COALESCE(date1, date2, date3) , COALESCE(date2, date1, date3) , COALESCE(date3, date1, date2) ) FROM my_test_table ```
You can use the `GREATEST` function, which returns the largest of the given n arguments: ``` SELECT GREATEST(date1, date2, date3) FROM table1 ```
Query to Find max of three columns in a row
[ "", "sql", "oracle", "plsql", "" ]
Using the below as a basis how would i work out a person age in months i not to sure how to go about changing this so the months is cacualated instead of years ``` IF cast(datepart(m, GETDATE()) as int) > cast(datepart(m,@in_DOB) as int) SET @age = cast(datediff(yyyy,@in_DOB,GETDATE()) as int) else...
Its my birthday today :) and I am `SELECT DATEDIFF(MONTH, '13 Nov 1963', GetDate())` months old. Whoops, too many beers already. **Update** ``` DECLARE @birthdate datetime DECLARE @months INT SELECT @birthdate = '13 Nov 1963' SELECT @months = DATEDIFF(MONTH, @birthdate, GETDATE()) - CASE WHEN DAY(@birthdate) > DAY(...
It's a bit of a mouthful, but we get the crude estimate just using [`DATEDIFF`](http://technet.microsoft.com/en-us/library/ms189794.aspx)1 - and then we adjust it if it's wrong: ``` select @age = DATEDIFF(month,@in_DOB,CURRENT_TIMESTAMP) - CASE WHEN DATEADD(month,DATEDIFF(month,@in_DOB,CURRENT_TIMESTAMP),@in_DOB) ...
Work out person age in months sql
[ "", "sql", "stored-procedures", "" ]
In ORACLE I am trying to get values from `PS_EMP_REVIEW_GOAL` with a `REVIEW_DT` between **01-01-YYYY** and **12-31-YYYY** from last year. I get the following error msg: ``` ORA-01843: not a valid month 01843. 00000 - "not a valid month" ``` \*Cause: \*Action: ``` SELECT ERG.REVIEW_DT, ERG.CAREER_GOAL from PS_EMP...
The problem is that `TRUNC(SYSDATE, 'YYYY')` will return whole date, which you then try to concatenate with day and month: ``` SELECT TRUNC(SYSDATE, 'YYYY') FROM dual; ``` ``` TRUNC(SYSDATE,'YYYY') --------------------- 01-01-2013 ``` What you should do instead is `EXTRACT` the year from `SYSDATE` and use the date f...
Another shorter option would be: ``` extract(year from ERG1.REVIEW_DT) = extract(year from current_date) - 1 ``` **BUT**: this would **not** use an an index on `ERG1.REVIEW_DT` so it might be to slow for your purposes. IN that case Przemyslaw's answer is much better, because that expression *can* use an index on that...
In ORACLE get values from 01-01-YYYY to 12-31-YYYY previous year
[ "", "sql", "oracle", "date", "" ]
I'm trying to better understand set-based logic and simplify a piece of code I'm working on. Here's an example of what I am currently working with (it doesn't work currently for reasons that will quickly become apparent): ``` SELECT userid, rn = ROW_NUMBER() OVER (ORDER BY username) FROM user WHERE u...
You can't call a stored procedure as part of another query, so it would be impossible to do what you're asking as a set-based operation without rewriting the stored procedures.
Several years ago I wrote a SQL-based utility specifically to address needs like this. It is detailed in this article at another site here: <http://www.sqlservercentral.com/scripts/Administration/69737/>. (If you want, I can include it here as well, but it is fairly long) Please note the following about it: 1. It is ...
Handling set-based operations in SQL
[ "", "sql", "sql-server", "t-sql", "set-based", "" ]
Recently i have migrated my postgres from 8.2 to 8.4. when I run my application and tried to login i am getting these error ``` ERROR [JDBCExceptionReporter] ERROR: function to_date(timestamp without time zone, unknown) does not exist ``` i had checked in my postgres by excecuting these to\_date function ``` SELECT...
It seems like all it needs is a conversion from timestamp to text as function definition is: to\_date(text,text). Perhaps in 8.2 this conversion from timestamp to text was already predefined. <http://www.postgresql.org/docs/8.4/static/functions-formatting.html>
Three year later. You can cast ``` SELECT to_date(cast(createddate as TEXT),'YYYY-MM-DD') FROM product_trainings; ```
Getting error function to_date(timestamp without time zone, unknown) does not exist
[ "", "sql", "database", "postgresql", "jdbc", "" ]
![Three of my database tables](https://i.stack.imgur.com/gahOP.png) ![Other three database tables](https://i.stack.imgur.com/m1FYQ.png) I have a problem where I need to select the Project Number, Controlling Department Number, Department Manager's Lname, address, and birthdate for each project located in Stafford. I ...
Basically, you're missing out the join on `DEPARTMENT` and `PROJECT`. I'd use explicit joins rather than the outdated `where` syntax: ``` select PROJECT.PNUMBER, PROJECT.DNUM, EMPLOYEE.LNAME, EMPLOYEE.ADDRESS -- and so on with the EMPLOYEE fields from PROJECT inner join DEPARTMENT on DEPARTMENT.DNUMB...
Try something like this ``` select p.pnumber, d.dnumber,e.lname, e.[address], e.bdate from department D inner join project P on D.dnumber = P.dnum inner join employee E on e.ssn = D.mgrssn where p.location = 'STAFFORD' ```
I need to select information form a database based on criteria that crosses multiple tables
[ "", "sql", "sql-server", "" ]
I'm trying to add a column to one of of my database tables, but there is a syntax error and I can't seem to find the problem... My current database table looks like this: ``` component + tag_id + item_id ------------|----------|----------- com_content | 23 | 2642 com_content | 26 | 3481 com_con...
The 'ALTER TABLE' bit must come first, and then each part must be seperated by a comma: ``` ALTER TABLE gitags_items DROP PRIMARY KEY, ADD COLUMN id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id,component,tag_id,item_id); ``` but I'm not sure if you can drop and create a primary key in the same staatement.
This one works fine, there was the problem with the commas, theres no need to drop the primary key since your going to set one yourself ``` ALTER TABLE gitags_items ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id,component,tag_id,item_id); ```
MySQL alter table add column with primary key syntax error
[ "", "mysql", "sql", "" ]
First, hope the title expresses the issue. Otherwise, any suggest is welcomed. My issue is I have the following table structure: ``` +----+------+------------------+-------------+ | ID | Name | recipient_sender | user | +----+------+------------------+-------------+ | 1 | A | 1 | X ...
Please try: ``` SELECT MIN(ID) ID Name, max(case when recipient_sender=1 then user else null end) sender, max(case when recipient_sender=2 then user else null end) recipient From yourTable group by Name ```
maybe you can try this: ``` select min(id) id, name, max(decode(recipient_sender, 1, user, '')) sender, max(decode(recipient_sender, 2, user, '')) recipient from t group by name ``` You can check a demo [here on SQLFiddle](http://sqlfiddle.com/#!4/c9a41/1).
divide a column into two based on another column value - ORACLE
[ "", "sql", "oracle", "" ]
I have two string columns `a` and `b` in a table `foo`. `select a, b from foo` returns values `a` and `b`. However, concatenation of `a` and `b` does not work. I tried : ``` select a || b from foo ``` and ``` select a||', '||b from foo ``` Update from comments: both columns are type `character(2)`.
The problem was in nulls in the values; then the concatenation does not work with nulls. The solution is as follows: ``` SELECT coalesce(a, '') || coalesce(b, '') FROM foo; ```
With [string types](https://www.postgresql.org/docs/current/datatype-character.html) (including `character(2)`), the displayed concatenation just works because, [quoting the manual:](https://www.postgresql.org/docs/current/functions-string.html) > [...] the string concatenation operator (`||`) accepts non-string > inp...
How to concatenate columns in a Postgres SELECT?
[ "", "sql", "postgresql", "types", "concatenation", "coalesce", "" ]
I have a SQL Server 2012 Enterprise setup issue and was so far unable to find a solution of my specific use case: I have two SQL servers, one in the United States and one in Germany. Both are being used for reading and writing and the task is to make them synchronized. The good news is, that while reading happens a lo...
Either [Merge Replication](http://technet.microsoft.com/en-us/library/ms152746.aspx), [Bidirectional Transactional Replication](http://technet.microsoft.com/en-us/library/ms151855.aspx), or [Peer-to-Peer Replication](http://technet.microsoft.com/en-us/library/ms151196.aspx) is the best fit here. Since writes can occur...
Yes, for this you can use `MergeReplication` or `Transactional Replication` They are both described in detail on the following page: <http://technet.microsoft.com/en-us/library/ms152531.aspx> Each Table must have one field set up as rowguid. The Requirement for this is that it is of type uniqueidentifier. You should ...
SQL Server 2012: synchronize two servers with writes to both
[ "", "sql", "sql-server-2012", "replication", "mirroring", "" ]
I'm trying to get a percent complete column in SQL for the following data. This is the results from my query. ``` work_order_no status orderqty complete precentcomplete WO-000076 Approved 20.0000 9 5201725 WO-000076 Approved 20.0000 10 15605175 WO-000078 ...
This should be what you want. The complete column should not be included in the GROUP BY, and should be summed. ``` SELECT DISTINCT wo.work_order_no, wos.status_description, wo.order_qty AS [ORDERQTY], SUM(p.good_tot_diff) AS [COMPLETE], (sum(p.good_tot_diff)/wo.order_qty) * 100 AS [PERCENTCOMPLETE] FROM wo_master AS ...
Try this: ``` Select wo.work_order_no, wos.status_description, wo.order_qty as [ORDERQTY], SUM(p.good_tot_diff) as [COMPLETE], SUM(p.good_tot_diff)/wo.order_qty as [PERCENTCOMPLETE] from wo_master as wo, process as p, wo_statuses as wos, so_children as soc, so_sales_orders as sos, c...
SQL Sum of 2 rows when 4 rows are returned
[ "", "sql", "sql-server-2008", "sum", "" ]
I'm getting the error "operand should be contain 1 column". Yes, I try to compare 1 column with 3, so is what I want to achieve possible? Clear exemple: I have a table test ``` id profile_id result_number 10 1232 3 10 3263 5 10 2222 4 10 2321 1 ``` Actually, I hav...
You can `JOIN` a subquery if it contains multiple rows: ``` SELECT profile_id FROM test t, ( SELECT result_number FROM test WHERE id = 10 AND profile_id = 2222 ) q WHERE t.result_number BETWEEN q.result_number-1 AND q.result_number+1 AND id = 10 ORDER BY t.result_number DESC ``` DEMO: <http://sqlfiddle.com/#!...
``` with a as ( SELECT `result_number`, profile_id FROM test WHERE id=10 AND `profile_id`=2222 ) SELECT PROFILE_ID FROM A UNION SELECT B.PROFILE_ID FROM TEST AS B, A WHERE B.RESULT_NUMBER = (A.RESULT_NUMBER - 1) UNION SELECT C.PROFILE_ID FROM TEST AS C, A WHERE C.RESULT_NUMBER = (A.RESULT_NUMBER + 1) ```
Operand should have 1 column in mysql
[ "", "mysql", "sql", "subquery", "" ]
Say I have a table where `Col2` is varchar ``` Col1 Col2 1 001,002 2 003,004,005 ``` I need to count the number of elements in Col2,and return it, if I do: ``` select --do something here with column-- from table ``` it'll give me: ``` 2 3 ```
So by counting the number of `,`s you have in Col2 and adding 1 to it would give you your answer. Below I get the length of Col2. Then I replace the `,`s with nothing and get that length. I take the first length and subtract the second length to get the total number of commas. Then simply add 1 to the result to get the...
If it's always formatted like that simply [count the number of commas](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions147.htm#sthref1418) and then add 1: ``` select regexp_count(col, ',') + 1 from table ```
Count the number of elements in a comma separated string in Oracle
[ "", "sql", "oracle", "" ]
Hey guys I have the below sample data which i want to query for. ``` MemberID AGEQ1 AGEQ2 AGEQ2 ----------------------------------------------------------------- 1217 2 null null 58458 3 2 null 58459 ...
If all of the columns are integers, you can take advantage of integer math - dividing the column by itself will yield 1, unless the value is NULL, in which case COALESCE can convert the resulting NULL to 0. ``` SELECT MemberID, COALESCE(AGEQ1 / AGEQ1, 0) + COALESCE(AGEQ2 / AGEQ2, 0) + COALESCE(AGEQ3 / AGE...
Try this: ``` select id, a+b+c+d+e+f from ( select id, case when age1 is null then 0 else 1 end a, case when age2 is null then 0 else 1 end b, case when age3 is null then 0 else 1 end c, case when age4 is null then 0 else 1 end d, case ...
Counting if data exists in a row
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I've already looked at these two questions: * [Grouping by Column with Dependence on another Column](https://stackoverflow.com/questions/13410052/grouping-by-column-with-dependence-on-another-column) * [MySQL GROUP BY with preference](https://stackoverflow.com/questions/1741866/mysql-group-by-with-preference) However...
You can use that MAX example, you just needed to "fake it". See here: <http://sqlfiddle.com/#!2/58688/5> ``` SELECT * FROM test JOIN (SELECT 'west' AS direction, 4 AS weight UNION SELECT 'north',3 UNION SELECT 'south',2 UNION SELECT 'east',1) AS priority ON priority.direction = te...
I came up with this solution, however, it is ugly. Anyway, you may try it: ``` CREATE TABLE test ( route INT, direction VARCHAR(20), operatorName VARCHAR(20) ); INSERT INTO test VALUES(95, 'east', 'James'); INSERT INTO test VALUES(95, 'west', 'Richard'); INSERT INTO test VALUES(95, 'north', 'Dave'); INSERT INTO...
MySQL group by with ordering/priority of another column
[ "", "mysql", "sql", "group-by", "sql-order-by", "" ]
I am trying to create a database that holds staff information such as their names, timesheets, holidays booked etc and also information about the projects the are carrying out and what companies the projects are for. My code is below: ``` CREATE TABLE IF NOT EXISTS tblcompany ( companyid INT(11) UNSIGNED NOT N...
Create the table tblproject first before you reference it. Besides the wrong table order,you need either a primary or unique key on referenced columns. [SQL fiddle](http://sqlfiddle.com/#!2/7c43d)
I think you will solve your problem creating your tables in the opposite ordersm, otherwise you will have the same issue with tblemployee. A Foreigh Key needs that the reference table exists already.
MySQL error 1215, what am I doing wrong?
[ "", "mysql", "sql", "database", "" ]
I don't understand why this query isn't working as expected. I have a horse table and file table. The file table has columns "fk\_object" and "fk\_id" so I can get records like fk\_object="horse\_photo" and fk\_id=725. The file table also has is\_default and position columns so I can grab the file (photo) that should b...
To answer your question in the comment to my first answer, no, you cannot order anything used in a join. You can't order a view, inline function, derived table, CTE, or a subquery without using restrictive commands. So, let me give this one more try. You want a query that returns one record per horse. If there is a de...
Your issue is that you are grouping by horse id but not using any aggregate functions on the other columns you are selecting, if you group on one column every other column you select has to be a sum, or max, or min, etc. This should work: ``` SELECT `horse`.`id`, `horse`.`name`, `file`.`id` AS `fid`, `file`.`is_defaul...
MySQL ordering join results
[ "", "mysql", "sql", "join", "group-by", "" ]
I am new to SQL. I have a syntax error and cannot seem to get the SQL Query System to agree with it: ``` select t.tracktitle from tracks t inner join titles ti inner join artists ar if (ar.artistname = "The Bullets ", 'yes', 'no') on ti.titleid = t.titleid; ``` I am trying to find all tracks by the artist name, "The ...
The `if` statement is the issue, as that type of syntax for SQL is called a `case` statement. That said, based on what you want, you should move that up to the `JOIN`: ``` SELECT Tracks.tracktitle FROM tracks Tracks INNER JOIN titles Titles ON Titles.titleid = Tracks.titleid INNER JOIN artists Artists ON Artists.artis...
Try this: ``` select t.tracktitle from tracks t inner join titles ti on ti.titleid = t.titleid inner join artists ar on ar.artistid = ti.artistid and ar.ArtistName = 'The Bullets' ``` If you need to check if record exists: ``` select t.tracktitle from tracks t inner join titles ti on ...
SQL Query INNER JOIN Syntax
[ "", "sql", "" ]