Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to understand indexes in MySQL. I know that an index created in a table can speed up executing queries and it can slow down the inserting and updating of rows. When creating an index, I used this query on a table called `authors` that contains (`AuthorNum`, `AuthorFName`, `AuthorLName`, ...) ``` Create in...
## The Anatomy of an Index An index is a distinct data structure within a database and is data redundancy. Its primary purpose is to provide an ordered representation of the indexed data through a logical ordering which is independent of the physical ordering. We do this using a doubly linked list and a tree structure...
Yes, generally you need an index on the column or columns that you compare in the `WHERE` clause of your queries to speed up queries. If you search by `AuthorFName`, then you create an index on that column. If they search by `AuthorLName`, then you create an index on that column. In this case though, maybe what you s...
Understanding Indexes in MySQL
[ "", "mysql", "sql", "indexing", "" ]
I have the following tables ``` vehicle (veh_num(PK), veh_desc) log (log_num(PK), veh_num(FK), log_date, log_complaint) log_line (log_num(PK,FK), logline_num(PK), emp_id(FK), logline_date,logline_action) part (part_code(PK), logline_num(FK), log_num(FK), part_desc) signout (signout_num(PK), part_co...
I think what you want to do is having the delete cascade into other tables. Take a look at this [How do I use cascade delete with SQL Server?](https://stackoverflow.com/questions/6260688/sql-server-cascade-delete)
Read this link <http://beginner-sql-tutorial.com/sql-integrity-constraints.htm> and have you tried join instead of subquery in query?
SQL, How to delete rows from related tables using a query?
[ "", "sql", "" ]
I have a requirement for our system to list all members that HAVE posted a coupon and all the users that HAVEN'T posted a coupon. I made an SQL script to pull the list of members who HAVE posted a coupon. Here is the code: ``` SELECT DISTINCT b.Email, b.FirstName, b.LastName, b.MemberDisplayName AS DisplayName, b.Memb...
List of Members who *have* posted a coupon. ``` SELECT Email , FirstName , LastName , MemberDisplayName As DisplayName , MemberID FROM Member WHERE SystemID = 1 AND Claimed = 'Y' AND Email IS NOT NULL AND EXISTS ( SELECT * FROM ClassAd WHERE PostType = 'CPN...
An outer join and test for null is the opposite of the join Note you need outer join to use on (not where) ``` SELECT DISTINCT b.Email, b.FirstName, b.LastName, b.MemberDisplayName AS DisplayName, b.MemberID FROM Member b Left Outer JOIN ClassAd a ON b.MemberID = a.MemberID AND a.PostType = 'CPN' AND DATEDIFF(...
How Do I List the Users who haven't posted in SQL
[ "", "sql", "t-sql", "" ]
I have to split one column (pipe delimited) into new columns. Ex: column 1: `Data|7-8|5` it should be split into ``` col2 col3 col4 Data 7-8 5 ``` Please help me to solve this.
Have a play with this. It's a little verbose but illustrates every step of the operation. I encourage you to ask any follow up questions you might have! ``` DECLARE @t table ( piped varchar(50) ) INSERT INTO @t (piped) VALUES ('pipe|delimited|values') , ('a|b|c'); ; WITH x AS ( SELECT piped , Ch...
test data:- ``` create table #test ( col1 varchar(50) ) go insert into #test values ('Data|7-8|5'), ('Data|asdsad|sad'), ('fish|c cx cx xc cc xc cx |ededededeed'), ('Data|iueroiheqroqer|ewoijewijewd5'), ('tune||5'), ('Data||') go ``` function (needs more defensive programming for malformed...
Split pipe delimited into new columns
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
The stored procedure below works correctly as expected. Returning True if "FleetBarcode" exists and False if it doesn't. However, when it returns it it displays it as below ``` (no column name) True ``` **My problem is** I need the "No Column Name" part to have a defined column name. Tried the method below so f...
Use ``` ALTER PROC [dbo].[usp_getjobs] @barcode AS NVARCHAR(20) AS SELECT CASE WHEN EXISTS(SELECT [FleetBarcode], [Deleted] FROM w_DeliveryItems WHERE FleetBarcode = @barcode AND Delete...
Get rid if the `SELECT`s in the `THEN`/`ELSE` blocks and use `AS` to give the column a name: ``` SELECT CASE WHEN EXISTS( ... THEN 'True') ELSE 'False') END AS [Exist] --<-- add name here ```
Return Value Column Name
[ "", "sql", "sql-server", "t-sql", "" ]
I was fiddling around with one of our databases earlier today and I was curious on how to do something in psql. Let's say I have a query like the following (with *value1* being a **text** type in *mytable*): ``` SELECT * FROM mytable WHERE value1::date < '2013-10-24'::date; ``` This works fine if all the rows contain...
Technically we can't assume left-to-right evaluation order of the WHERE clauses, which means that in such a clause: ``` WHERE value1 ~ '^\d{4}-\d{2}-\d{2}$' AND value1::date < '2013-10-24'::date ``` the planner may decide to evaluate `value1::date` first and the execution will error out before testing the regexp. Sho...
You can use like-pattern or regex to pre-filter only `value1`s looking like dates: ``` SELECT * FROM mytable WHERE value1 like '____-__-__' and value1::date < '2013-10-24'::date; SELECT * FROM mytable WHERE value1 similar to '[1-2][0-9]{3}-[0-1][0-9]-[0-3][0-9]' and value1::date < '2013-10-24'::date; ``` Here ...
Querying on text values being casted into dates in postgresql
[ "", "sql", "postgresql", "" ]
I want to bring back the county Id and the county name. How can I fix this query? ``` DECLARE @test int = 0; select CASE (@test) when 0 then (SELECT co.Id, co.Description FROM Dictionary.Counties as co INNER JOIN CountyCollaboration as cc on cc.CountyId = co.Id ...
You can only return one expression from a CASE statement. Try using IF/ELSE instead. The CASE statement in T-SQL is not a control flow statement like CASE/SWITCH in many programming languages.
I suggest restructuring your query to look like this. ``` select id, country from (select co.id , co.country , case @test code for test goes here end caseresult from all that stuff you have as a subquery in your question ) derivedtable ```
sql Case statement bring back multiple values
[ "", "sql", "t-sql", "" ]
I have master table with several details tables. I need to check if each of the details tables have any rows for given ID. Right now I am going through all the tables and checking if count>0 but there must be a better way. ``` SELECT COUNT(*) FROM Table1 WHERE ID=3; SELECT COUNT(*) FROM Table2 WHERE ID=3; ... SELECT C...
If you really want one *result set* you can do: ``` DECLARE @ID INT SET @ID = 3 SELECT 'Table1' TableName, COUNT(*) FROM Table1 WHERE ID=@ID; UNION SELECT 'Table2' TableName, COUNT(*) FROM Table2 WHERE ID=@ID; UNION ... UNION SELECT 'TableN' TableName, COUNT(*) FROM TableN WHERE ID=@ID; ``` I don't see a way to *not...
``` WITH CTE AS ( SELECT 'T1' AS Name, COUNT(*) AS Total FROM Table1 WHERE ID=3 UNION ALL SELECT 'T2' AS Name, COUNT(*) AS Total FROM Table2 WHERE ID=3 UNION ALL ... UNION ALL SELECT 'Tn' AS Name, COUNT(*) AS Total FROM TableN WHERE ID=3; ) Select * from CTE where Total > 0 ```
How to check if multiple tables have rows for given ID
[ "", "sql", "" ]
Here is my code ``` SELECT ID, Name, Phone FROM Table1 LEFT JOIN Table2 ON Table1.ID = Table2.ID WHERE Table1.ID = 12 AND Table2.IsDefault = 1 ``` The problem happens when Table2 is null, so, the query returns nothing. How do I leave the last part of the query `AND Table2.IsDefault = 1` optional? I've tried to sh...
``` SELECT ID, Name, Phone FROM Table1 LEFT JOIN Table2 ON Table1.ID = Table2.ID AND Table2.IsDefault = 1 WHERE Table1.ID = 12 ```
``` AND COALESCE(Table2.IsDefault,1) = 1 ``` Reading the comments, it looks like your best solution is actually to move the condition to the join: ``` SELECT ID, Name, Phone FROM Table1 LEFT JOIN Table2 ON Table1.ID = Table2.ID AND Table2.IsDefault = 1 WHERE Table1.ID = 12 ``` Because it's an OUTER join, you'll s...
SQL Server LEFT JOIN and WHERE clause
[ "", "sql", "sql-server", "left-join", "" ]
I need to select a value of field `State` for next month. Field `Month` is char(6). Ex: `201310`. This is what I have and it doesn't work: `SELECT Code, Name, (SELECT State FROM dbo.ShiftList WHERE (MONTH(CONVERT(Date, Month)) = MONTH(GETDATE()) + 1)) AS SLNM FROM dbo.Shops`
For the performance issues it's rather perform manipulations with variables and not with data in the table. In this case your query can be like the following: ``` SELECT Code, Name, (SELECT State FROM dbo.ShiftList WHERE MONTH = cast(year(dateadd(month, 1, getdate())) * 100 + month(dateadd...
Both the current answers have one major problem - the functions they call on the columns means that indices will (very likely) be ignored. I prefer a SARGable condition, thank you: ``` SELECT state FROM dbo.ShiftList WHERE month = FORMAT(DATEADD(month, 1, GETDATE()), 'yyyyMM') ``` (Have a [SQL Fiddle Example](http:/...
Select field by next month(char6)
[ "", "sql", "sql-server", "" ]
I am returning 250,000 records in about 1:10 seconds... too long for a Job? I feel like SQL Server should be faster.. ``` SELECT ColOne FROM TableA WITH (nolock) WHERE EXISTS (SELECT ColOne FROM VIEW_1 WITH (nolock) WHERE LastDate < GETDATE() - 30) ``` Any...
Assuming that the tables from the View are the ones also in the select I would suggest. Add an index to table dbo.IDValueTable\_LASTSEEN for the field LastSeen. Forget about the VIEW, is not adding value in this case and it actually slows the query (why calculate the max of lastseen if later you are already filtering...
As @valex points out in his comment I think youe `EXISTS` condition is wrong. If a record exists where `LastDate < GETDATE() - 30` then you'll get the whole table back - otherwise you'll get nothing. I think you want (with table names added for clarity) ``` SELECT ColOne FROM TableA WITH (nolock) WHERE Tabl...
any improvements to SQL query with subquery of view?
[ "", "sql", "sql-server", "" ]
I have a little problem with this recursive CTE, it works fine except when I have a user without root readable rights means no entry for this element. So if I run this query on a user with rights just on the leaves inside the tree the level part of this query won't work correctly. It will show the real **level** hiera...
You haven't told us how you know whether a user has rights to a given id. That is a necessary piece of information. I'm going to put some code below that assumes you add a column to your query called *hasRights* and that this column will have a zero value if the user does not have rights and a value of one if they do. ...
Try to perform the following select and let me know if it is your desired result: ``` SELECT *, DENSE_RANK() OVER (PARTITION BY t.user_id ORDER BY t.LEVEL ASC) -1 as RelativeUserLevel FROM Tree AS t JOIN UserTable AS ut ON ut.id = t.user_id AND ut.user_id = '141F-4BC6-8934' ORDER BY Sort ```
Recursive cte sql with for hierarchy level
[ "", "sql", "sql-server-2008", "common-table-expression", "" ]
I have a column in sql server 2012. The column has date stored in varchar. The date data looks like this: dd/mm/yyyy However there is a catch. The data that is within the column is in refusing to convert. Details investigation reveals that some are convertible to date mode and others are not (may be due to date stored...
As per your comments, since you are certain about the string format (`dd/mm/yyyy`) you have in the column, I suspect your **problem could be due to a leading/trailing space**. Try this with `Ltrim()`, `Rtrim()` and `Isdate()` functions. If you get any date `01/01/1900` (Assuming this date is not in your field) in the ...
The date format you have in the db (dd/mm/yyyy) is 103. So you should try ``` SELECT convert(datetime, '31/10/2013', 103) ``` As per your clarifications, it seems you need the data in yyyy-mm-dd format. so please try below. ``` SELECT convert(varchar(max),(convert(datetime, '31/10/2013', 103)), 120) ```
How to covert to varchar column to date time where column is in mixed mode
[ "", "sql", "sql-server", "date", "type-conversion", "" ]
I have a table named `Customers` with columns `FirstName, LastName, Email` Let's pretend I have the customer: John | Williams | johnW1234@gmail.com Now how do I have to create my query so that if I search for: ``` "williams" => match "will john" => Match "will john 55" => NO match "will 1234" =>...
Seems like you want to do something like that: ``` select * from Customers where (FirstName like concat('%','john', '%') and LastName like concat('%','smith', '%')) or (LastName like concat('%','john', '%') and FirstName like concat('%','smith', '%')) ``` The parts: `john` and `smith` (in the query) are the differen...
I think this works: ``` select * from Customers where (_search_ regexp '^[^ ]+ [^ ]+$' or _search_ regexp '^[^ ]+$') and (LastName like concat(substring_index(_search_, ' ', 1), '%')) or FirstName like concat(substring_index(_search_, ' ', -1), '%'))); ```
Create search query
[ "", "mysql", "sql", "search", "" ]
Is there any way to call **count** on a distinct composite PK with Postgres? I am getting the following error and do not know why. ``` SQL: SQLSTATE[42883]: Undefined function: 7 ERROR: function count(character varying, integer) does not exist LINE 1: SELECT COUNT(DISTINCT "t".id, "t".library_id) FROM "ab_colle... ^ H...
``` SELECT COUNT(DISTINCT ROW("t".id, "t".library_id)) FROM "ab_collection" "t" WHERE t.library_id=1 ``` from here <https://github.com/yiisoft/yii/issues/3004#issuecomment-27601733>
I don't think you can use `COUNT(col1, col2,...)`. This would need to be two seperate like `COUNT(col1), COUNT(col2)`. I don't think it will therefore work on a composite key. > ...count(character varying, integer) does not exist... Tells you simply you cannot use the function because it's invalid (though the syntax ...
Postgresql COUNT() on distinct composite PK
[ "", "sql", "postgresql", "" ]
``` FirstName LastName University Bob Brown Aviation Kate Dylan Economic Tommy Loren Aviation ``` University have default value : **Aviation** . Have stored procedure where insert values to table, in procedure call have 3 parametres : ``` @declare firstname v...
if your default name of "University" column will always be **Aviation**, I would suggest this approach. Set a default value constraint for "University" column, if the value is null it will automatically insert the default value. ``` ALTER TABLE myTbl ADD CONSTRAINT DF_UName DEFAULT N'Aviation' FOR University ``` and...
MS SQL allows you to set default value for parameters in stored procedure: ``` CREATE PROCEDURE MyProc @firstName varchar(50), @lastName varchar (50), @university varchar(50) = 'Aviation' AS INSERT INTO myTbl (FirstName,LastName,University) VALUES (@firstname,@lastname,@university); ``` You can us...
How to insert values if some is empty
[ "", "sql", "sql-server", "" ]
I've just got a case where I need to use a computed column in the `WHERE` of another column's query I need to do something like this: ``` SELECT CONVERT(Date, RequestedOn) AS [Date], COUNT(*), (SELECT COUNT(*) FROM CalculatorLog WHERE CONVERT(Date, RequestedOn) = [Date] AND <other_static_conditions>) AS [Co...
Just sum 1 for the condition and 0 otherwise: ``` SELECT CONVERT(Date, RequestedOn) AS [Date], COUNT(*), SUM(CASE WHEN <other_static_conditions> THEN 1 ELSE 0 END) AS [Count] FROM CalculatorLog Group by CONVERT(Date, RequestedOn) Order by [Date] DESC ```
Replace [Date] column with CONVERT(Date, CL.RequestedOn) in subquery like ``` SELECT CONVERT(Date, CL.RequestedOn) AS [Date], (SELECT COUNT(*) FROM CalculatorLog WHERE CONVERT(Date, RequestedOn) = CONVERT(Date, CL.RequestedOn) AND <other_static_conditions>) AS [Count] FROM CalculatorLog CL Group by CONVER...
use a computed column in another column which is a query itself
[ "", "sql", "sql-server-2008", "t-sql", "" ]
If I have a `user` table and a `post` table, and I want to count how many posts a user has posted today, I can think of two ways. The first is to send a SQL query to count how many `post` records that belong to a `user` is created today. The second is to have a `count` table, that has three columns: `user_id`, `num_p...
The first one should be fine if the number of users and posts in your system are not too many. But if there are too many users and posts, you may want to consider for the second option, as it will be faster. The drawback is that it will require more space to store the data.
Second alternative is more redundant, I wouldn't recommend it except if you have performance problems with the first one. (Redundancy can cause inconsistencies, it is bad in rdbms world.)
DIfference between counting records and counter variable in database
[ "", "sql", "database", "performance", "rdbms", "redundancy", "" ]
I'm looking for a way to skip rows in PostgreSQL. Two ways I could do this are using: ``` SELECT * FROM table WHERE id % 5 = 0 ``` However I'd have to fetch sequential rows to properly skip. For instance if I fetch row (with ids) 0,3,5, it would not skip 4 out of 5 rows, but instead result in (ids) 0 and 5. Or skip...
If you use PostgreSQL, you can use [`row_number()`](http://www.postgresql.org/docs/8.4/static/functions-window.html): ``` SELECT t.* FROM ( SELECT *, row_number() OVER(ORDER BY id ASC) AS row FROM yourtable ) t WHERE t.row % 5 = 0 ```
If n is large enough (like 1000), you can consider using [WITH RECURSIVE](http://www.postgresql.org/docs/9.4/static/queries-with.html) queries like: ``` WITH RECURSIVE foo(name) AS (SELECT name FROM people ORDER BY name LIMIT 1) UNION (SELECT (SELECT name FROM people WHERE name >= foo.name ...
Skip every nth result row in PostgreSQL
[ "", "sql", "postgresql", "" ]
I'm wondering what is the best way to do the following code: ``` select Id,Id2 from someTable where Id in (select someId from someTable2) or Id2 in (select someId from someTable2) ``` I checked the execution plan and I can see two table scans(no index) for someTable2. The solution I'm looking is not related to...
use `JOIN`, ``` SELECT DISTINCT a.ID, a.ID2 FROM someTable a INNER JOIN someTable2 b ON b.someID IN (a.id, a.id2) ``` **UPDATE** ``` SELECT ID, ID2 FROM someTable a INNER JOIN someTable2 b ON b.someID = a.id UNION SELECT ID, ID2 FROM someTable a INNER JOIN someTable2 b ON b.someID = a.id2 ```
``` SELECT id , id2 FROM sometable WHERE EXISTS ( SELECT someid FROM sometable2 WHERE someid IN (sometable.id, sometable.id2) ) ```
SQL "In" condition with subquery
[ "", "sql", "" ]
Here is a link to a fiddle that currently works, it just seems like there is a better way to do this that I am not seeing: <http://sqlfiddle.com/#!2/396f2/6> ``` --- Sample schema CREATE TABLE `jobs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `salary` int(11) DEFAULT NULL, PRIMA...
Build the result set you want (people to people\_jobs to jobs), then left join to `people_jobs` a second time, where the person is the same but the job is always "artist". Filter out the resulting non-null rows, because those are people who have an artist job. e.g. ``` SELECT p.name, j.title FROM people p LEFT JOIN (...
I am unsure on how you would be using your query without a nested sub query to exclude artists, but a small optimisation would be to remove the unnecessary join to people in your sub query, I.e. ``` SELECT p.name, j.title FROM people p LEFT JOIN people_jobs pj ON pj.pid = p.id LEFT JOIN jobs j ON j.id = pj.ji...
Using MySQL how can I better select all people and their jobs excluding anyone who has a particular job?
[ "", "mysql", "sql", "" ]
I have this query and i want to select the inverse of what that select. ``` SELECT Guide.id FROM Guide INNER JOIN GuideAvailability ON Guide.id = GuideAvailability.guideId WHERE GuideAvailability.startDate IN (1377946800) GROUP BY GuideAvailability.guideId HAVING COUNT(DISTINCT GuideAvailability.id) = 1 ``` Is there ...
Simply use this query: ``` SELECT * FROM Guide where id NOT IN ( SELECT Guide.id FROM Guide INNER JOIN GuideAvailability ON Guide.id = GuideAvailability.guideId WHERE GuideAvailability.startDate IN (1377946800) GROUP BY GuideAvailability.guideId HAVING COUNT...
MAy be you are looking for this ``` SELECT Guide.id FROM Guide INNER JOIN GuideAvailability ON Guide.id = GuideAvailability.guideId WHERE GuideAvailability.startDate NOT IN (1377946800) GROUP BY GuideAvailability.guideId HAVING COUNT(DISTINCT GuideAvailability.id) <> 1 ```
SQL Statement - SELECT the inverse of this query
[ "", "mysql", "sql", "inverse-transform", "" ]
I've been stuck on this one for a little bit. I have 3 tables and want to match tables 2 and 3 to table 1 on different columns. ``` tasks: id | item1_id | item2_id -------------------------------------------- 1 | 4 | 5 2 | 5 | 6 3 | 6 | 7 -...
Why are you doing a `cross join`? Just do two `left join`s: ``` SELECT tasks.id AS taskID, item1.name AS item1Name, item2.name AS item2Name FROM tasks LEFT JOIN item1 on tasks.item1_id = item1.id LEFT JOIN item2 on tasks.item2_id = item2.id LEFT JOIN users on users.task_id = tasks.id LEFT...
Simply like that : ``` SELECT tasks.is AS taskId, item1.item1_name AS item1Name, item2.item2_name AS item2Name FROM tasks JOIN users ON users.task_id = tasks.id JOIN notes ON notes.task_id = tasks.id LEFT JOIN item1 ON item1.id = tasks.item1_id LEFT JOIN item2 ON item2.id = tasks.item2_id ```
How to LEFT JOIN 3 tables ON multiple columns
[ "", "mysql", "sql", "left-join", "" ]
I have some code where variable used in the WHERE clause could be nullable. As a result I have to query data using IF ELSE to check for NULL. Is there anyway of writing in in one query? ``` DECLARE @OrderID UNIQUEIDENTIFIER IF @OrderID IS NULL BEGIN SELECT * FROM Customers WHERE OrderID IS NULL END ELSE...
``` SELECT * FROM Customers WHERE EXISTS (SELECT OrderID INTERSECT SELECT @OrderID) ``` Will do this efficiently. See [Undocumented Query Plans: Equality Comparisons](http://web.archive.org/web/20180422151947/http://sqlblog.com:80/blogs/paul_white/archive/2011/06/22/undocumented-query-plans-equality-comparison...
Assuming you want all records where order\_id is either null or equal to a provided order ID, using COALESCE will keep the original order ID if not null but yield the provided order ID if it *was* null. That is then compared with the provided order ID. ``` SELECT * FROM customers c WHERE COALESCE(c.order_id, @OrderID)...
Compare NULL to NULL in SQL Server
[ "", "sql", "sql-server", "t-sql", "null", "" ]
I have the following tables ``` table 2 with a fk to table 1 table 3 with a fk to table 1 ``` In table 2 I have two rows linked to table 1 In table 3 I have one row linked table 1 I am trying to produce a table that has ``` | table1 pk | table 2 pk | null | | table1 pk | table 2 pk | null | | table1 pk | null | ...
One unusual solution is ``` select coalesce(t2.tab1_id, t3.tab1_id) pk, t2.pk, t3.pk from table2 t2 full join table3 t3 on t3.tab1_id = t2.tab1_id where exists (select * from table1 where pk in (t2.tab1_id, t3.tab1_id) ``` NOTE (Edit) As noted by Andriy M in comment, the where clause only ...
You could use a join to the result of a union: ``` SELECT t1.table1pk, t23.table2pk, t23.table3pk FROM table1 t1 INNER JOIN ( SELECT table2pk, NULL AS table3pk, table1fk FROM table2 UNION ALL SELECT NULL AS table2pk, table3pk, table1fk FROM table3 ) t23 ON t1.table1pk = t23.table1fk ; ``` Or you cou...
Multiple join not joining as expected
[ "", "sql", "oracle", "join", "left-join", "" ]
I've created two tables, Customers and Records. Records has a foreign key constraint on customerID. When I try inserting a record to a customer that already exists, it gives me this error: ``` Message (The INSERT statement conflicted with the FOREIGN KEY constraint "FK_REC_cstmr_int_id". The conflict occurred in dat...
Are you using the same connection for all the queries/statements above? The problem *might* just be related to an uncommitted transaction.
That value does not exist in the referenced table. Here's a scenario that does not have `10` in your referenced table: **Set up** ``` create table cst_new_customer ( cstmr_int_id int not null primary key); insert into cst_new_customer (cstmr_int_id) values (9), (11); create table rec_new_records ( cstmr_int_id ...
FOREIGN KEY constraint error on insert even though entry already exists
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Remove the Decimal values ``` select cast(val as integer),val from table ``` and I tried round that is also not working pls tell me the way to solve this. ``` select ROUND(2.9,0) from dual 24 23.8331134259259 31 30.8322222222222 31 30.8321990740741 31 31.1120023148148 31 31.1119791666667 28 28.0590046296296 3...
Hi try truncate function ``` TRUNC( number, [ decimal_places ] ) ```
Are you looking for [`FLOOR`](http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions067.htm#SQLRF00643)? > FLOOR returns the largest integer equal to or less than n. The number n can always be written as the sum of an integer k and a positive fraction f such that 0 <= f < 1 and n = k + f. The value of FLOOR i...
Decimal to Integer in sql
[ "", "sql", "oracle", "" ]
I have a simple **table** with two fields ( **name** and **id** ), it already consists of some values. How do i check if the **name** already exists and if it exists then check for **id** if it matches with the corresponding name. Thanks in advance.
For php and mysql: ``` $sql = "select * from `table` where name = "' username '""; $query = mysql_query($sql); if(mysql_num_rows($query)){ //username is present } else { //username is not present } ```
Try ``` Select id from table where name =? ``` if you get an **id** the name exist, if not, the name doesnt
How do I check if a record already exists in sql table?
[ "", "mysql", "sql", "" ]
I wish to query a column in a table in every database that the table exists. So far I have the following but am not sure where to go from here: ``` DECLARE @tblName VARCHAR(5000) = 'myTable' SELECT name FROM sys.databases WHERE CASE WHEN state_desc = 'ONLINE' THEN OBJECT_ID(QUOTENAME(name) + '.[dbo].['+@t...
sp\_foreachdatabase makes a nice shortcut: <http://www.mssqltips.com/sqlservertip/1414/run-same-command-on-all-sql-server-databases-without-cursors/>
`sp_MSForEachDb` can be buggy, skip databases and other weird stuff. There is an alternative procedure [here](http://www.mssqltips.com/sqlservertip/2201/making-a-more-reliable-and-flexible-spmsforeachdb/) that has a very similar usage. Another way would be ``` DECLARE @tbl SYSNAME = 'sys.objects' DECLARE @sql NVARCHA...
How to query a column in a table in all databases
[ "", "sql", "sql-server", "t-sql", "" ]
Is there any way to compare the generated range column in the mysql query ? ``` SELECT ue.bundle,ue.timestamp,b.id,bv.id as bundleVersionId,bv.start_date,bv.end_date, bv.type,ue.type from ( SELECT bundle,timestamp,tenant, case when Document_Id ='' then 'potrait' WHEN Document_Id<>'' then 'persisted' end as type fr...
Stick to one encoding/collation for your entire system. Right now you seem to be using UTF8 one place and latin1 in another place. Convert the latter to use UTF8 as well and you'll be good. You can change the collation to UTF8 using ``` alter table <some_table> convert to character set utf8 collate utf8_general_ci; `...
I think sometimes the issue is we use different orm utilities to generate table and then we want to test queries either by mysql command line or MySql workbench, then this problem comes due to differences of table collation and the command line or app we use. simple way is to define your variables (ones used to test th...
Illegal mix of collations error in mysql query
[ "", "mysql", "sql", "collation", "" ]
Recently upgraded to using PostgreSQL 9.3.1 to leverage the JSONfunctionalities. In my table I have a json type column that has a structure like this: ``` { "id": "123", "name": "foo", "emails":[ { "id": "123", "address": "somethinghere" }, { "id": "456", "add...
For **Postgres 9.4+** see adamc's later answer. Or: * [Query for array elements inside JSON type](https://stackoverflow.com/questions/22736742/query-for-array-elements-inside-json-type/22737710#22737710) ### Original answer for Postgres 9.3 Yes, that's possible: ``` SELECT * FROM tbl t, json_array_elements(t.json...
With a JSONB column in Postgres 9.4+ you can use the contains operator `@>` to query for an element in an array: ``` SELECT * FROM jsontest WHERE data @> '{ "emails": [{ "id": "123" }] }'; ``` See [Query for array elements inside JSON type](https://stackoverflow.com/a/22737710/740997) for more details. Here is a wor...
Query for element of array in JSON column
[ "", "sql", "json", "postgresql", "postgresql-9.3", "lateral", "" ]
I am trying to insert null with my query into a datetime column which allows null. My query works fine (I think). But its putting 1900-01-01 00:00:00.000 instead of null into the datetime column. Why is this happening and how do I fix it ? I created my own table to test this and nulling is NOT a problem there. But, it...
To see all the triggers in the database, use the following query: ``` select t.name as [TableName], tr.name as [TriggerName], m.[definition] from sys.triggers tr join sys.sql_modules m on m.object_id = tr.object_id join sys.tables t on t.object_id = tr.parent_id ``` To see all the default constraints, ...
When inserting using INSERT query, don't specify the column name and don't give any value. That should insert null in the field. For example, If `Entry_Date` is my nullable datetime column in `abc` table, then my insert statement would be like: ``` Insert into abc (Entry_Id, Entry_Value) values (1,1000); ``` By not ...
Cannot insert null into datetime in sql server
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "" ]
The table : ``` CREATE TABLE GUESTS ( GUEST_ID int IDENTITY(1,1) PRIMARY KEY, GUEST_NAME VARCHAR(50), GUEST_SURNAME VARCHAR(50), ADRESS VARCHAR(100), CITY VARCHAR(50), CITY_CODE VARCHAR(10), COUNTRY VARCHAR(50), STATUS VARCHAR(20), COMMENT nvarchar(max)...
Take a look at [this article](https://www.simple-talk.com/sql/database-administration/pop-rivetts-sql-server-faq-no.5-pop-on-the-audit-trail/) on Simple-talk.com by [Pop Rivett](https://www.simple-talk.com/author/pop-rivett/). It walks you through creating a generic trigger that will log the OLDVALUE and the NEWVALUE f...
This is the code with two bug fixes. The first bug fix was mentioned by Royi Namir in the comment on the accepted answer to this question. The bug is described on StackOverflow at [Bug in Trigger Code](https://chat.stackexchange.com/transcript/message/34774768#34774768). The second one was found by @Fandango68 and fixe...
Log record changes in SQL server in an audit table
[ "", "sql", "sql-server", "" ]
I go this error message when I run this query ``` SELECT name,state FROM customers WHERE state ‌IN ('CA','NC','NY') ``` Error SQL query: Documentation ``` SELECT name, state FROM customers WHERE state ‌IN( 'CA', 'NC', 'NY' ) LIMIT 0 , 30 ``` MySQL said: Documentation > #1064 - You have an error in your SQL synt...
Remove the `=` after `IN` ``` SELECT name, state FROM customers WHERE state ‌IN ('CA','NC','NY') ```
``` SELECT name,state FROM customers WHERE state ‌IN ('CA','NC','NY') ``` You can not use the '=' with an IN
My sql syntax error 1064 -can't find what is wrong
[ "", "mysql", "sql", "" ]
Lets say I have a sql table in the format: ``` id INT PRIMARY KEY AUTO_INCREMENT, action TINYINT NOT NULL, user_id INT NOT NULL ``` I would like to build a query that produces the same result as the following: ``` SELECT (SELECT COUNT(*), action FROM table WHERE action=1 AND user_id=1), (SELECT COUNT(*), act...
If I understand the question correctly, this is what you're looking for: ``` SELECT action, COUNT(*) FROM your_table WHERE user_id = 1 GROUP BY action ```
You can use GROUP BY: ``` SELECT COUNT(*) as Count, action as Action FROM table1 WHERE user_id = 1 GROUP BY action ``` This will produce a row for each unique action, and in that row have a column Count being the count of rows with that unique action. In the example above, all user\_id conditions are =1, so if t...
Select count of distinct column in table
[ "", "mysql", "sql", "select", "count", "distinct", "" ]
**Table:** ``` ID AppType AppSubType Factor 1 SC CD 1.0000000000 2 SC CD 2.0000000000 3 SC NULL 3.0000000000 4 SC NULL 4.0000000000 ``` **Query:** ``` declare @ast varchar(10) set @ast = null select * from tbl where AppType = 'SC' and AppSubType = ISNULL(@ast, AppSubType) ``` ...
Abviously @ast is null and Isnull would exchange null with other value, so you shouldn't expect @ast to be not null. If your AppSubType is null , so the result become null but `AppSubType=null` doesn't mean because `AppSubType is null` is true. Because null is not a value so it cant work with equal. for your expected r...
You can write a case condition in where clause as: ``` declare @ast varchar(10) set @ast = null select * from tbl where AppType = 'SC' and 1= case when isnull(@ast ,'') = '' and isnull(AppSubType ,'') = '' then 1 when AppSubType = ISNULL(@ast, AppSubType) then 1 else 0 end ```
Using ISNULL in where Clause doesn't return records with NULL field
[ "", "sql", "sql-server-2008", "isnull", "" ]
I have been trying for a while now to get a similar method to `GETDATE()` in DB2 for i. So far I have found the following: ``` current date current timestamp current time ``` Would it be possible for me to: ``` select specific, columns from table where datefield = current date - 1 day ``` Is this the most effici...
This will give you yesterday's date: ``` SELECT CURRENT DATE - 1 DAY FROM sysibm.sysdummy1 ```
If you want to know a certain date range as an alternative you can try the TIMESTAMPDIFF scalar function, read syntax diagramSkip visual syntax diagram The parameter: 16 indicates it will evaluate per days The next example determines a range of 70 days as of now. ``` WHERE (TIMESTAMPDIFF(16, CHAR(SYSDATE- CURRENT DAT...
GETDATE() method for DB2
[ "", "sql", "sql-server", "t-sql", "ibm-midrange", "db2-400", "" ]
every time I want to round to 2 decimal places when it comes to zeros it doesnt want to round it... how could I round it to 2 decimal places with zeros at the end which would give me 92.00 instead of just 92 ??? ``` SELECT ROUND(COLUMN_NAME,2) FROM .... ``` it's giving me ``` COLUMN_NAME 92 ``` but I want ``` COLU...
you may try the TO\_CHAR function to convert the result e.g. ``` SELECT TO_CHAR(92, '99.99') AS RES FROM DUAL SELECT TO_CHAR(92.258, '99.99') AS RES FROM DUAL ``` Hope it helps
This works too. The below statement rounds to two decimal places. SELECT ROUND(92.258,2) from dual;
Rounding to 2 decimal places in SQL
[ "", "sql", "oracle", "rounding", "" ]
This is the opposite of what most "random order" questions are about. I want to select data from a database in random order. But I want to be able to repeat certain selects, getting the same order again. ### Current (random) select: ``` SELECT custId, rand() as random from ( SELECT DISTINCT custId FROM dummy ) ``...
You could try and implement the Multiply-With-Carry PseudoRandomNumberGenerator. The C version goes like this (source: [Wikipedia](http://en.wikipedia.org/wiki/Random_number_generation)): ``` m_w = <choose-initializer>; /* must not be zero, nor 0x464fffff */ m_z = <choose-initializer>; /* must not be zero, nor 0...
Not sure if this applies in non-SQL Server, but typically when you use a `RAND()` function, you can specify a seed. Everytime you specify the same seed, the randomization will be the same. So, it sounds like you just need to store the seed number and use that each time to get the same set of random numbers. [MSDN Art...
Shuffle data in a repeatable way (ability to get the same "random" order again)
[ "", "sql", "math", "random", "shuffle", "" ]
I have the following date in the my sql table ``` 2013-04-01 00:00:00.000 2013-06-19 15:57:10.357 2013-06-19 15:57:10.370 2013-06-19 15:57:10.383 2013-06-19 15:57:10.397 2013-04-01 00:00:00.000 2013-04-01 00:00:00.000 2013-04-01 00:00:00.000 2013-06-19 15:57:10.410 ``` My question is: How do i make it to `2013-04-01...
Unless your source data *always* has a time of midnight (which I doubt, otherwise the time wouldn't be important), adding 12 hours could result in an incorrect date. You can do it by taking parts from two different format codes: 120 - ODBC canonical - `yyyy-mm-dd hh:mi:ss`(24h) 109 - Default + milliseconds - `mon dd...
The easiest way is to add 12 hours. And the easiest way to do that is to add 0.5: ``` select mydate + 0.5; ``` Your sample code doesn't really make sense. First, it is working on the current date value, rather than a column in the data. Also, it is missing a length on the first argument. *Always* include length when ...
sql date format convert from 2013-04-01 00:00:00.000 to 2013-04-01 12:00:00
[ "", "sql", "sql-server-2008", "" ]
I have searched and i cannot seem to find the answer. I have tried using different styles, but none of them give me exactly what i want. I am trying to convert a datetime, that I have calculated. However I need it to display the full month. ``` SELECT CONVERT(VARCHAR(25),DATEADD(dd, @codelife, getdate()),107) ``` th...
Nathan's answer seems solid, however if you're using SQL Server 2012 you can make use of the `FORMAT()` function: ``` SELECT FORMAT(GETDATE(),'MMMM dd, yyyy') ``` Or in your case: ``` SELECT FORMAT(DATEADD(dd, @codelife, getdate()),'MMMM dd, yyyy') ```
I always use <http://www.sql-server-helper.com/tips/date-formats.aspx> as my reference ``` SELECT DATENAME(MM, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY] ``` I would declare your date as a variable and do something like: ``` DECLARE @myDate DATETIME SET @myDate = DateAdd(dd, @co...
convert datetime to display full month
[ "", "sql", "sql-server", "date", "datetime", "type-conversion", "" ]
Please notice this is not **MySQL** I am talking about **BigQuery** I need to perform the following operation on Google Big-Query ``` SELECT * FROM searchable.keyword AS kw1, (SELECT keyword From searchable.keyword GROUP BY keyword ORDER BY keyword DESC) AS kw2 WHERE kw1.keyword CONTAINS(kw2.keyword) # or eve...
There are two issues... the first is that bigquery only supports equi-join -- that is, you can only join on exact equality. The second is that comma is UNION ALL not JOIN (this is unfortunate legacy behavior) To do this, you'll need to compute the full cross join: ``` (SELECT keyword, 1 as cross FROM searchable.keywor...
2 ways I would tackle this: 1. Use the Lag and Lead functions. this way you could run on a single table, and extract following records with same values (it will work only for =, or contains in the beginning of the string.) 2. Create a full cross join by using a fictive join condition, and then put your condition in th...
How to select matches in the same table in BigQuery without Join
[ "", "sql", "google-bigquery", "" ]
I have got a table where i need to handle the ordering with two columns. the first one holds the days from 1 to 7. this is the first column to order. and then there is another column that i need to order but this time i need it to start ordering from 06:00:00. ``` SELECT * FROM stream ORDER BY day,start="06"; ```...
You can just add 25 to hour if it is less than 6 in the `ORDER BY` clasue, take a look: ``` SELECT * FROM stream ORDER BY day, CASE WHEN hour(start) < 6 THEN hour(start) + 25 ELSE hour(start) END ``` This way, all the values before the `06:00:00` will be at the end. SQ...
You could make a CASE to your order query, take a look at this post ! ``` Order BY CASE 1 THEN ORDER BY CASE 2 ... ``` [Order by Case](https://stackoverflow.com/questions/5276038/sql-order-by-months-starting-with-this-month)
How can i order my rows from (first) a column and then (secondly) another column which is a specific starting time?
[ "", "mysql", "sql", "" ]
I'm totally stumped here, I hope I haven't overlooked an answer elsewhere. I have two tables, `asset` and `purchase_order`. **asset** ``` asset_key | description | purchase_order_key ``` **purchase\_order** ``` purchase_order_key | order_number | number_of_assets ``` I'm trying to get a list of purchase orders, e...
You can use a subquery: ``` SELECT * FROM purchase_order WHERE number_of_assets > ( SELECT COUNT(*) FROM asset WHERE asset.purchase_order_key = purchase_order.purchase_order_key ) ```
You need to do a `COUNT` on the `assets` joined to the PO table, and then compare them with the recorded number of assets. ``` SELECT PO.purchase_order_key, COUNT(A.purchase_order_key) FROM purchase_order PO LEFT JOIN asset A ON PO.purchase_order_key = A.purchase_order_key GROUP BY PO.purchase_order_key, PO.number...
SQL - Select record count from column value in separate table
[ "", "sql", "sql-server", "database", "t-sql", "" ]
I am using SQL\*Plus with Oracle8i Enterprise Edition Release 8.1.7.4.0. I have a table `customer_address`: ``` no - customer number type - 0 main, 1 delivery, 2 invoice email - customer e-mail address ``` Every customer has an e-mail address set as type 0, for e.g.: ``` SELECT no, type, email FROM customer_addre...
Maybe something like this? ``` insert into customer_address (no,type,email, primarykeyfieldofthetable, otherfields) select no,'1',email, sequenceofprimarykey.nextval, otherfields from customer_address where type='0' ```
if you incluse all the fields in the correct order you can also avoid to specify them after the table name ``` INSERT INTO customer_address SELECT no, '1', email, otherfields FORM customer_address WHERE cunu ='1' AND type='0' ```
SQL INSERT\UPDATE query using existing data
[ "", "sql", "oracle", "sqlplus", "" ]
I am using SAS EG to do this. This is the input table that I have: ``` ref11 ref2 Col1 Col2 Col3 Col4 Col5 Col6 A B 41 42 D E 63 65 68 X Y 23 25 55 89 99 K L 12 22 U V 22 88 11...
Please see below the code that worked. Solution provided by JT85. ``` set test; array in col1-col6; array out $ c1-c6; j=1; do i=1 to 5; if in(i) ne ' ' then do; out(j)=in(i); j+1; end; end; run; ``` Thanks
[assuming the order of the values is not important as long as the missing values are to one side and non-missing values to another] You could use the [`call sortn`](http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003106054.htm) routine. `call sortn` essentially sorts values that are in...
row function in SAS SQL
[ "", "sql", "sas", "enterprise-guide", "" ]
I was trying to feed the following commands to MySQL CLI with , which seems to be good, however when I added one more table, it complained there was an error in syntax. Here are the commands ``` CREATE TABLE IF NOT EXISTS User( uid INT, name VARCHAR(64) UNIQUE, birthday date, PRIMARY K...
``` FOREIGN KEY(accept_uid) REFERENCES User(uid),<-- Comma should be removed ``` Try this: ``` CREATE TABLE friendship( invite_uid INT, accept_uid INT, start_date DATE, PRIMARY KEY(invite_uid, accept_uid), FOREIGN KEY(invite_uid) REFERENCES User(uid), FOREIGN KEY(acc...
Check the last line of your code ``` FOREIGN KEY(accept_uid) REFERENCES User(uid), ``` Remove the comma at the end.
error in SQL syntax create table
[ "", "mysql", "sql", "" ]
I have table => ``` Main Table : MT ================ PK SPK Name D1 ============== 1, 0, XYZ, 0 1, 1, A, 99 1, 2, B, 88 1, 3, C, 77 2, 0, NULL, 0 2, 1, NULL, 99 2, 2, Z, 88 ``` From that I want to get ``` Result Table : RT ================ PK SPK Name D1 ============== 1, 0, XYZ, 264 1, 1, A, 99 1, 2, B, 88 1, 3...
Use ranking function (sqlserver 2005+) ``` select PK, SPK, Name, case when SPK = 0 then sum(D1) over (partition by pk) else D1 end as D1 from table order by PK, SPK ```
``` SELECT t.pk, t.spk, t.name, CASE WHEN t.spk = 0 THEN ts.d1 ELSE t.d1 END AS d1 FROM your_table t LEFT JOIN ( SELECT tt.pk, SUM(tt.d1) AS d1 FROM your_table tt GROUP BY tt.pk ) ts ON t.pk = ts.pk ```
Get conditional SUM in first row
[ "", "sql", "database", "sql-server-2008", "t-sql", "view", "" ]
I have 2 tables that doesn't have primary keys. These 2 tables have same number of rows. I want to create a new table from getting some columns from table1 and some columns from table 2. I want to combine first row from table1 and first row from table2. Below is example **TABLE1** ``` ACOL1 ACOL2 ACOL3 A1 A2 A3 B1 B2...
You cannot use `rownum` as a column name, giving it an alias solves the problem ``` create table COMBINED_TABLE AS select a.ACOL1, b.BCOL2, b.BCOL3 from (select ACOL1,rownum rn from TABLE1) a, (select BCOL2, BCOL3, rownum rn from TABLE2) b WHERE a.rn = b.rn ```
``` create table combined_table as select a.acol1, b.bcol2, b.bcol3 from ( select acol1, row_number() over (order by acol1) as rn from table1 ) a join ( select bcol2, bcol3, row_number() over (order by bcol1) as rn from table2 ) b on a.rn = b.rn ``` Using `row_number()` is more robust than `rownum` as...
CREATE New Table from existing tables in Oracle 11g
[ "", "sql", "oracle", "" ]
I'm trying to create a select to not show when it has a PDF in another column from my other table ``` SELECT * from blogs ``` ``` |blogs| |id| |number| 1 423423 2 432422 3 123233 4 324233 ``` ``` SELECT b.id, p.id, p.file_name FROM posts p, blogs b ``` ``` |posts| |id| |blog_id| |file_na...
You need a `LEFT JOIN`. Try this out: ``` SELECT b.* FROM blogs b LEFT JOIN posts p ON b.id = p.blog_id WHERE p.blog_id IS NULL ``` Output: ``` | ID | NUMBER | |----|--------| | 3 | 123233 | | 4 | 324233 | ``` Fiddle [here](http://sqlfiddle.com/#!2/7c804/1).
``` SELECT b.id, b.number FROM posts p INNER JOIN blogs b ON b.id= p.blog_id WHERE p.file_name NOT LIKE '%.pdf' ``` Try this. This is how it works in t-SQL not sure if its the same in MySQL
How can I do a select to not show when it has PDF in other table?
[ "", "mysql", "sql", "" ]
I have a four tables, TopLevelParent, two mid level tables MidParentA and MidParentB, and a Child table which can have a parent of MidParentA or MidParentB (One or the other midParent must be in place). Both mid level tables have a parent table of TopLevelParent. The Top Level table look like this: ``` TopLevelId | N...
Here is what I did in the end, which got the execution time down from 52 secs to 4 secs. ``` SELECT * FROM ( SELECT tpl.*, a.MidParentAId as 'MidParentId', 1 as 'IsMidParentA' FROM TopLevelParent tpl INNER JOIN MidParentA a ON a.TopLevelParentId = tpl.TopLevelParentID UNION SELECT tpl.*, b.MidParen...
Given how little of the query is being exposed; a very rough rule of thumb is to replace an Or with a Union to avoid table scanning. ``` Select.. LEFT JOIN Child c ON c.ParentAId = a.ParentAId union Select.. left Join Child c ON c.ParentBId = b.ParentBId ```
SQL Server Left Join With 'Or' Operator
[ "", "sql", "sql-server", "t-sql", "left-join", "" ]
Currently at the moment I have managed to join two tables to retrieve the information that is need. I have now decided to try and retrieve another piece of information from a another table ( users.user\_id ) but the query I'm trying to use doesn't seem to work. If someone could help with the query would be great. Here...
Try this: ``` SELECT films.movie_title, films.rating, films.actor, reviewed.review, users.name FROM films LEFT JOIN reviewed ON films.movie_id=reviewed.movie_id LEFT JOIN users ON films.user_id=users.user_id ```
Is it possible that you want to have the user\_id in your reviews table? That way you'd have the following: 1. table of movies; only one per movie 2. table of users; only one per user 3. table of reviews; one per review linked to a user and to a movie The reviews table would now have the rating, the review itself, a ...
Selecting data from three tables
[ "", "mysql", "sql", "" ]
As an example, let's say I have a fact table with two dimensions and one measure **FactMoney table** --- ProjectKey int PersonKey int CashAmount money --- The two dimensions are defined like this: **DimProject (a type 0 dimension - i.e. static)** --- ProjectKey int ProjectName varchar(50) --- **DimPerson (...
About your main question: I would say that you need to add the categories in the category table (probably copying them from the old person row). So you can continue to classify the person in the new (changed) state. About a change of category: I would prefer to do not add a person row but add an initial-validity and a...
But what do we do with the person's categories? Do we need to add more rows to the bridge table every time a new person version pops up? Only, if you want to change the person's category. Because, only the person names changes not the person key in DimPerson Table. The relation between DimPerson and PersonCategory is ...
Data Warehouse - Slowly Changing Dimensions with Many to Many Relationships
[ "", "sql", "many-to-many", "ssas", "data-warehouse", "scd", "" ]
I'm new to mysql and have a question about joins and adding stuff. I have the following tables: `books` and `genres` The books table looks as such: ``` id | name | pages | genre_id ``` The genres table: ``` id | name | category_id ``` I want to get the genre that has the most pages. So if genre1 has 5 books and...
This will get the genres and total number of pages in them, in descending order, `LIMIT 1` will select the top one. ``` SELECT g.name, SUM(b.pages) AS p_total FROM books b JOIN genres g ON g.id = b.genre_id GROUP BY g.id ORDER BY p_total DESC LIMIT 1 ```
Here is the [**SQL Fiddle**](http://sqlfiddle.com/#!2/3a296d/1/0) that illustrates the below query ``` SELECT g.name, SUM(b.pages) FROM books AS b INNER JOIN genres AS g ON b.genre_id = g.id GROUP BY g.id ORDER BY SUM(b.pages) DESC LIMIT 1 ```
SQL query joining tables and comparing sums to return max
[ "", "mysql", "sql", "join", "" ]
I want to have the SELECTed query return in order by Number. This is currently what is being returned: ![enter image description here](https://i.stack.imgur.com/f3RBr.png) And here is the current query: ``` SELECT [Number] + ' - ' + SUBSTRING([Title], 1, 40) AS [StoryName] ,[PK_Story] FROM Story STY INNER J...
``` ORDER BY CAST(SUBSTRING([Number], 6, LEN([number])-5) AS INT) ```
The problem is that your list is being sorted as a string, and you want it sorted numerically. Try something like this: ``` SELECT [Number] + ' - ' + SUBSTRING([Title], 1, 40) AS [StoryName] ,[PK_Story], CAST(SUBSTRING([Number], 5, 3) AS int) AS [CMNumber] FROM Story STY INNER JOIN Task TSK ON TSK.StoryId = STY.P...
SELECT query not returning in desired order
[ "", "sql", "sql-server", "" ]
I am working with a query: ``` USE SCRUMAPI2 DECLARE @userParam VARCHAR(100) ,@startDateParam DATETIME ,@endDateParam DATETIME ,@orgTeamPK VARCHAR(100) ,@teamId VARCHAR(100) ,@productId VARCHAR(100) ,@search VARCHAR(200) SET @userParam = 'David Tunnell (tunnelld)' SET @startDateParam = '2013-...
I suspect that `STY.Effort` and `TSK.OriginalEstimateHours` (in the `SELECT` clause for rows of `RowType` 3) are numeric. From the documentation for [`UNION`](http://technet.microsoft.com/en-us/library/ms180026.aspx): > The definitions of the columns that are part of a UNION operation do not have to be the same, but ...
> Their types are INT and BIGINT, If you want an empty string, and not `0` or `NULL`, you will need to use the `CAST` or `CONVERT` functions to cast the column to a varchar type. You can't put an empty string in a number column. You may also need to then use a `CASE` statement to tranform a `0` string into an empty st...
Zero being returned instead of empty string
[ "", "sql", "sql-server", "" ]
I want to move all the table from one database to another with primary key and all other keys using SQL queries. I am using SQL Server 2005 and I got a SQL queries to move the table but the keys are not moved. And my queries is as follows ``` set @cSQL='Select Name from SRCDB.sys.tables where Type=''U''' Insert int...
The following T-SQL statement move all the table, primary key and foreign key from one database to another. Notice that the method SELECT \* INTO FROM ... WHERE 1 = 2 does not create COMPUTED columns and user-data types. Suppose also that all primary keys are clustered ``` --ROLLBACK SET XACT_ABORT ON BEGIN TRAN DECLA...
You can generate customized script of Source Database and run the script for Destination Database. Here is the [link](https://stackoverflow.com/questions/844586/preserve-primary-key-values-in-database?answertab=active#tab-top) and slightly better [one][2] Get the complete table and then perform the `delete` queries o...
Moving table from one database to another with primary key and other keys
[ "", "sql", "sql-server-2005", "" ]
I am working on a twitter like app. In this app, a user will have other user as followers and they can see followers posts. I have following tables: ![enter image description here](https://i.stack.imgur.com/xcP8S.jpg) According to the design, a user can have other users as followers (kind of like Unary relationship)....
``` select u.FirstName, u.LastName, up.PostStatus from UserPosts as up inner join Users as u on u.UserID = up.UserID where up.UserID = @UserID or exists ( select * from Followers as f where f.FollowerID = up.UserID and f.UserID = @UserID ) ```
The following gives you a) User 1 posts b) Posts from anyone following User 1. ``` SELECT p.* FROM posts p WHERE userID = 1 UNION ALL SELECT pf.* FROM posts pf JOIN followers f ON pf.userID = f.followerID WHERE f.userID = 1 ```
how to retrieve all data from joining table using parent key
[ "", ".net", "sql", "sql-server", "" ]
For this problem, I'm using Access as a front end for SQL Server, and calling Access through Excel VBA, although I can use a direct ADO connection if there are some T-SQL specific functions that would be more useful here. I have a table that logs state changes for a set of items, e.g.: ``` +-------+-------+----------...
You have a problem using Access-only functionality. But, if you have SQL Server 2012, you can use `lead()`/`lag()` functionality. There is another way, just using `row_number()`, which is available since SQL Server 2005. Here is the idea. Enumerate the rows within each `docId` first by `state` and also by `date`. If t...
In his otherwise excellent answer, Gordon Linoff said: > You have a problem using Access-only functionality Really? For the given data, which I've put in a table called [StateChanges]: ``` docID state date ----- ----- ---------- 103 5 2013-10-15 103 6 2013-10-18 102 3 2013-10-22 ...
How to find out if a field's values for a given item are only increasing?
[ "", "sql", "sql-server", "ms-access", "ms-access-2010", "" ]
I am trying to create a table, which consist of following columns: * `DateID`, which should start to count on 20130101. (1st JAN 2013) and end up at 20131231 (31st DEC 2013). * `Year`, which has to stay 2013 (easy to handle by using VALUE). * `Month`, which should start to count at 01 and ends up at 12. * `Day`, which...
A recursive CTE can do this for you: ``` DECLARE @dates TABLE ( isodate varchar(8), theyear int, themonth int, thedate int ); WITH datecte AS ( SELECT 0 AS cnt, CAST('1 Jan 1900' AS DATE) AS startdate UNION ALL SELECT cnt + 1, DATEADD(D, 1, startdate) FROM datecte WHERE D...
To answer your base question, no, there's no way to "manipulate" auto-increment like that. It can have a constant seed value and constant increment, but that's it. You *could* manipulate it with an `INSERT` trigger that "resets" the increment seed, but I would not recommend it. You don't need auto-increment - you can ...
How to constrain an auto increment (creating a calendar)
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I need to isolate text before the first numeric in a column using T-SQL in SQL Server. E.g. ``` StreetName 11A-D ``` I would like to receive the result: ``` StreetName ``` My challenge is to find out which char number the first numeric is. Any suggestions?
Please try: ``` declare @var nvarchar(100)='StreetName 11A-D'; Select SUBSTRING(@var, 1, PatIndex('%[0-9]%', @var)-1) ```
``` select left(street, patindex('%_[0-9]%', street + '1')) from ( select 'StreetName 11A-D' street union all select 'StreetName' street ) x ``` Result: ``` StreetName StreetName ```
Return first char in string that is number
[ "", "sql", "sql-server", "" ]
I'm trying to run the following fairly simple query in SQL Server Management Studio: ``` SELECT TOP 1000 * FROM master.sys.procedures as procs left join master.sys.parameters as params on procs.object_id = params.object_id ``` This seems totally correct, but I keep getting the following error: > Msg 102, ...
Such unexpected problems can appear when you copy the code from a web page or email and the text contains unprintable characters like individual CR or LF and non-breaking spaces.
Panagiotis Kanavos is right, sometimes copy and paste T-SQL can make appear unwanted characters... I finally found a simple and fast way (only Notepad++ needed) to detect which character is wrong, without having to manually rewrite the whole statement: there is no need to save any file to disk. It's pretty quick, in ...
Incorrect syntax near ''
[ "", "sql", "sql-server", "ssms", "" ]
I need to create a function in SQL server that returns daylight savings time start datetime and daylight savings time end datetime. I've come across a few examples on the web, however they all are using the 1st date of March and the 1st date of November and thats not technically correct. Daylight savings time begins ...
**As pointed out in comments, right now (March 2022) this calculation looks likely to change next year: US may not switch off of DST in the fall.** Don't forget that daylight saving time schedules change depending on country, and also are subject to change over the years: the current (as of 2013 through 2022) US syste...
Personally, I think it's easier to find the first Sunday in November than it is to find the second Sunday in March. Luckily, if you find one, you can find the other because there's always 238 days between them. So here's a handy function to find the end of Dst: ``` create function GetDstEnd ( ...
How to create Daylight Savings time Start and End function in SQL Server
[ "", "sql", "sql-server-2008", "dst", "sql-function", "" ]
``` CREATE TABLE questions ( qid INT AUTO_INCREMENT, submitterId VARCHAR(8) NOT NULL, approverId VARCHAR(8) NOT NULL, questionText TEXT NOT NULL UNIQUE, answerA VARCHAR(100) NOT NULL, answerB VARCHAR(100) NOT NULL, answerC VARCHAR(100) NOT NULL, answerD VARCHAR(100) NOT NULL, difficulty INT NOT NULL, category INT NOT N...
1. There can be only one auto column and it must be defined as a key. 2. BLOB/TEXT columns in key specification can't be used without a key length. Thus, the correct SQL DDL shall be: ``` CREATE TABLE questions ( qid INT AUTO_INCREMENT PRIMARY KEY, submitterId VARCHAR(8) NOT NULL, approverId VARCHAR(8) NO...
An idtentity-column must be declared as PRIMARY or UNIQUE
Error in MySQL query
[ "", "mysql", "sql", "" ]
I got a problem. I use SQL Server 2008 Express. When new row is inserted into a table the `IDENT_CURRENT` function returns correct value (last inserted row id). But when the last inserted row is deleted (`DELETE FROM REPORT WHERE ID='last_inserted_id'`) the `IDENT_CURRENT` function returns id of the deleted row. It do...
This is working as expected. The function returns the last identity value used, even if it's been deleted. Here's an excerpt from Microsoft's documentation: IDENT\_CURRENT returns the last identity value generated for a specific table in any session and any scope.
Identity always goes up. It won't go down if you delete rows. Plus it can have 'blanks' in values. Read this for detailes <http://technet.microsoft.com/en-us/library/ms186775.aspx>
ident_current shows wrong last inserted id
[ "", "sql", "sql-server", "sql-server-2008", "last-insert-id", "" ]
First SQL Query (Total Memroy) ``` SELECT Nodes.NodeID AS NodeID, Nodes.TotalMemory AS TotalMemory, Nodes.Caption AS NodeName FROM (Nodes INNER JOIN Volumes ON (Nodes.NodeID = Volumes.NodeID)) ``` Second SQL Query (Number of CPU on nodes) ``` SELECT N.Caption, COUNT(DISTINCT CPUIndex) FROM CPUMultiLoad_Detail C...
In the general case just use a join and a CTE ``` WITH PartOne AS ( SELECT N.NodeID, COUNT(DISTINCT CPU.Index) as [Count] FROM CPUMultiLoad_Detail CPU WITH(NOLOCK) JOIN Nodes N ON CPU.NodeID = N.NodeID GROUP BY N.Caption ) SELECT Nodes.NodeID Nodes.TotalMemory , Nodes.Caption AS NodeName, ...
For the same situation i used the Temp Table SELECT ..... FROM.... INTO #Temp1 GO SELECT ..... FROM.... INTO #Temp2 GO SELECT ..... FROM #Temp1, #Temp2 WHERE #Temp1.NodeID = #Temp2.NodeID Remember to Drop the Temp Tables like This: DROP Table #Temp1 DROP Table #Temp2
SQL Join two query results
[ "", "sql", "database", "sql-server-2008", "" ]
I want to pull out top 3 selling products for different product category per tag. Data looks like this: ``` tag | product_name | product_category | order_count tag1 | product1 | category1 | 100 tag1 | product2 | category2 | 80 tag1 | product3 | category2 | 60 tag1 | product4 | cat...
First ROW\_NUMBER removes duplicate rows per tag and product\_category, second ROW\_NUMBER selects top 3 selling products per tag ``` ;WITH cte AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY tag, product_category ORDER BY order_count DESC) AS rn FROM yourtable ), cte2 AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY ...
You can use `RANK()` (or `ROW_NUMBER()`) as long as you use `PARTITION BY`. This in combination with `TOP()` should work well assuming you're using SQL Server 2005+: ``` with cte as ( select tag, product_name, product_category, order_count, rank() over (partition by product_category ...
SQL-select top 3 values per group WITH CONDITION
[ "", "sql", "sql-server", "greatest-n-per-group", "" ]
I am building a sports system in PHP/MySQL. With some help on StackOverFlow, I have built it. I have OW\_SPORTS\_GAMES table which has all details about each games played with team Id and scores. Here is the structure. ![enter image description here](https://i.stack.imgur.com/pl0tc.png) Also there is another table O...
Your problem is that you are limiting the JOIN to only return games where the prediction is correct; ``` AND p.teamId = IF(g.homeTeamScore > g.awayTeamScore , g.homeTeam, IF(g.homeTeamScore < g.awayTeamScore , g.awayTeam, NULL)) ``` However, your assumption when calculating the number of wrong predictions is that the...
I think the main root of your problem is use of RIGHT join when joining in the predictions -- this will give you rows of data for games that you did not want to count... Try changing that to a LEFT join and let us know. **Update:** Ouch down-voted for pointing out that the RIGHT join was pulling in extra records? Ther...
User Guessing System for Sports - SQL Issue
[ "", "mysql", "sql", "" ]
I am learning SQL using MYSQL and as a practice I want to get the name of employees who has a dependent whose first letter of his/her name matches the middle name of that employee. Also they must be of same gender. Here is how I have done it so far: ``` SELECT e.fname , e.minit , e.lname FROM employee e WHERE EXISTS ...
``` SELECT e.fname e.minit , e.lname , dependent_name FROM employee AS e INNER JOIN dependent ON SUBSTRING(e.minit,1,1) = SUBSTRING(dependent_name,1,1) AND e.sex=dependent.sex AND essn=e.ssn ```
``` select e.fname, e.minit, e.lname, d.name from employee e inner join dependent d on e.substring(e.minit, 1, 1) = substring(d.name, 1, 1) and e.sex = d.sex ```
MYSQL employee and dependent
[ "", "mysql", "sql", "" ]
``` SELECT pnumber, pname, COUNT(*) FROM project INNER JOIN works_on ON pno=pnumber INNER JOIN department ON dnumber=dnum GROUP BY pnumber ``` Right now, mysql will return the project number and name, along with the number of employees who are working on it. What I want to do is that mysql only count employees from ...
If Barmar's and Shafeeq's suggestion of using a `WHERE` clause won't work for you (for example, if you need to include all departments in your result, but only count people from department 5) you can use this: ``` SUM(IF(dnum=5, 1, 0)) AS CountFromDepartment5 ``` So we'd have: ``` SELECT pnumber, pname, COUNT(*) AS...
You can use `WHERE` ``` SELECT pnumber, pname, COUNT(*) FROM project JOIN works_on ON pno = pnumber JOIN department ON dnumber=dnum WHERE dnumber = 5 GROUP BY pnumber ``` **EDIT** ``` SELECT pnumber, pname, COUNT(*),SUM(IF(dnumber=5, 1, 0)) AS count5 FROM project JOIN works_on ON pno = pnumber JOIN department O...
Count with condition-mysql
[ "", "mysql", "sql", "" ]
I have t-sql which is working fine on the local sql server if I run the same t-sql on the remote sql server hosting the database ginving the error I tried a lot of changes but nothing works for me finally I decide to write on Stack Exchange. I cretaed my local database with the script from the server so I hope no cha...
``` Create Table #TempAppliedData( IdNo1 [nvarchar](50) COLLATE DATABASE_DEFAULT, ``` Here you are creating column which has the default collation of your hosting `tempdb`. Apparently your own database uses a CI collation, while the hosting service is deployed with a CS collation. Use an explicit collation in your s...
Just add after value where you have an error `COLLATE SQL_Latin1_General_CP1_CS_AS`
Collation Conflict error working on local sql not on server hosting database
[ "", "sql", "sql-server", "t-sql", "" ]
What is the difference between ? ``` SELECT u.id,u.name,u.email,d.city,d.state from users u, userdetails d where u.id=d.uid SELECT u.id,u.name,u.email,d.city,d.state from users u join userdetails d on u.id=d.uid ``` Are they both different style of writing join ? which one is faster ?
This: ``` SELECT u.id,u.name,u.email,d.city,d.state FROM users u, userdetails d ``` Is [Cartesian product](http://en.wikipedia.org/wiki/Cartesian_product) (the set of all ordered pairs). When you add the where clause: ``` SELECT u.id,u.name,u.email,d.city,d.state FROM users u, userdetails d WHERE u.id=d.uid ``` ...
You would want to go for the joining option as it gives you more control, look in to the different types of join (Inner, Left etc) and you can work out exactly what you need for your example. (I suspect Inner would be best) <http://www.w3schools.com/sql/sql_join.asp>
SQL selecting from two tables
[ "", "sql", "join", "" ]
I am trying to make an excel macro that will give me the following function in Excel: ``` =SQL("SELECT heading_1 FROM Table1 WHERE heading_2='foo'") ``` Allowing me to search (and maybe even insert) data in my Workbook's Tables using SQL queries. This is what I have done so far: ``` Sub SQL() Dim cn As ADODB.Conne...
One thing you may be able to do is get the address of the dynamic named range, and use that as the input in your SQL string. Something like: ``` Sheets("shtName").range("namedRangeName").Address ``` Which will spit out an address string, something like `$A$1:$A$8` *Edit:* As I said in my comment below, you can dyna...
``` Public Function GetRange(ByVal sListName As String) As String Dim oListObject As ListObject Dim wb As Workbook Dim ws As Worksheet Set wb = ThisWorkbook For Each ws In wb.Sheets For Each oListObject In ws.ListObjects If oListObject.Name = sListName Then GetRange = "[" & ws.Name & "$" & Re...
Performing SQL queries on an Excel Table within a Workbook with VBA Macro
[ "", "sql", "vba", "excel", "" ]
I am trying to select random rows from a column however I have one problem, I would like to select a row where `title != '';` The below isn't giving me what I want. I put `and r1.title != '';` This shows empty titles. I am echoing `$row['image_one'];` later. I have two rows, the first one has image\_one and title, the ...
My best guess is that the maximum id in the table has an empty title. As a result, no records are matching when the random number generator is producing a value near 1, and your code is confusing a NULL value/empty row with an empty string. You can fix this by modifying the query to some other method of getting a rand...
This is because `NULL` is not the same as `''`. If you need to find not empty titles, you need to change the query to: ``` SELECT r1.id, title, price, image_one FROM table AS r1 JOIN (SELECT (RAND() * (SELECT MAX(id) FROM table)) AS id) AS r2 W...
where clause doesn't work mysql
[ "", "mysql", "sql", "" ]
I have this case : ![enter image description here](https://i.stack.imgur.com/PQsUJ.jpg) `UserSettings` is not really a junction table since it only has one FK, which is gonna be unique, one `UserSettings` for one User. Should `UserSettings` have `UserId` marked as Primary Key even if `UserId` is a unique FK or is it ...
If you want to ensure this "which is gonna be unique" requirement then you'll need to define UserID either as UNIQUE or as Primary Key constraint.
With few exceptions, every table should have a primary key. So yes, I would make it a primary key even if it is also a foreign key.
Should a table have a PK when it has a unique FK?
[ "", "sql", "sql-server", "foreign-keys", "primary-key", "" ]
I have a table that has the follow data structure: ``` terminal | load_time_mns | vehicle _________________________________________ Terminal 1 | 3 | AA Terminal 2 | 10 | AF Terminal 1 | 1 | BF Terminal 6 | 3 | QRS Terminal 6 | 1.4 ...
Something like this might help: **Query 1**: ``` SELECT terminal, count(CASE WHEN load_time_mns >= 0 AND load_time_mns < 1 THEN 1 END) [0-1 mns], count(CASE WHEN load_time_mns >= 1 AND load_time_mns < 2 THEN 1 END) [1-2 mns], count(CASE WHEN load_time_mns >= 2 AND load_time_mns < 3 THEN 1 END) [2-3 mns] FROM ...
You can use a bit of dynamic SQL to extend this to the complete result set. Create a table called intervals to store the intervals: ``` Create Table ex ( terminal varchar(10), load_time_mns decimal(10, 2), vehicle varchar(3) ); Insert Into ex values ('Terminal 1', 3, 'AA'), ('Terminal 2', 10, 'AF'...
CrossTab Query / Pivot Table in MS SQL?
[ "", "sql", "sql-server-2008", "pivot", "" ]
I would like to insert a range of values into a pair of SQL tables, with data requiring some pre-processing (like attaching a common time stamp and some revamp of the data in both tables). Ideally I prefer to shield my code from direct SQL statements, opting to use stored procedures instead. How could I pass these valu...
You can use table-valued parameters in the stored procedure. This allows to pass a table as a parameter so you can define the structure of the parameter as you want. See 'Use Table-Valued Parameters (Database Engine)' on MSDN - <http://technet.microsoft.com/en-us/library/bb510489.aspx> To call such a SP, see, e.g., [...
Send the data over as XML and convert it into multiple rows. Something like ``` SELECT Tbl.Col.value('(span/b)[1]', 'nvarchar(max)') AS [key], Tbl.Col.value('(span/var)[1]', 'nvarchar(max)') AS [position], Tbl.Col.value('@title', 'nvarchar(max)') AS [tooltip], Tbl.Col.value('(code)[1]', 'nvarchar(max)') A...
How to pass rows of values into SQL Server stored procedure?
[ "", "sql", "sql-server", "stored-procedures", "sql-server-2012", "parameter-passing", "" ]
``` SELECT PERSONALINFO.FN, PERSONALINFO.SN FROM PERSONALINFO JOIN BOOKING ON BOOKED.EMAIL = PERSONALINFO.EMAIL HAVING COUNT(BOOKEDE.EMAIL) > 2 ``` I am using sqldeveloper to try and count how many times an email comes up in the booking database, and if the email comes up more than twice it will ...
When you use an aggregate function, you need a `GROUP BY` clause ``` SELECT PERSONALINFO.FIRSTNAME, PERSONALINFO.SECONDNAME FROM PERSONALINFO JOIN BOOKING ON BOOKING.EMAIL = PERSONALINFO.EMAIL GROUP BY PERSONALINFO.FIRSTNAME, PERSONALINFO.SECONDNAME HAVING COUNT(BOOKING.EMAIL) > 2 ```
``` SELECT PL.FIRSTNAME, PL.SECONDNAME, PL.EMAIL FROM PERSONALINFO PL INNER JOIN BOOKING B ON B.EMAIL = PL.EMAIL WHERE COUNT(B.EMAIL)>2 ; ```
SQL developer counting and showing info
[ "", "sql", "oracle", "oracle-sqldeveloper", "" ]
I use Oracle PL/SQL and need to check is there client with ID in table. (YES or NO). I made a query to table and it returns row with this ID into `v_klient`. For example, in my table there's no ID with number 2. But I can't compare this, because error "no data found". Need to skip this error and compare with `if` state...
You could try it this way: ``` DECLARE id_kl_original NUMBER := 2; // this ID v_klient klients%rowtype; // Variable for query return BEGIN BEGIN SELECT * INTO v_klient FROM klients WHERE id_klient=id_kl_original; // query DBMS_OUTPUT.put_line(v_klient.id_klient); /* SO...
This will work: ``` DECLARE id_kl_original NUMBER := 2; // this ID i NUMBER; // Variable for query return BEGIN SELECT count(*) INTO i FROM klients WHERE id_klient=id_kl_original; // query IF (i = 0) THEN DBMS_OUTPUT.put_line(' There are no clients with this ID.'); /* SOME ACTIONS*/ ELS...
skip error in PL/SQL Oracle database
[ "", "sql", "database", "oracle", "plsql", "" ]
I need to group a column based on the starting letter, and then count how many start with the respective letter. This is rather easy, but my question would be, how do you set a name to a column so you don't have to write the same thing multiple times? Here's my code: ``` SELECT substr(p_nev,1,1) firstLetter, count(su...
As an alternative you can also use a common table expression: ``` with letters as ( SELECT substr(p_nev,1,1) as firstLetter from pizza ) select firstletter, count(*) as cnt from letters group by firstletter order by firstletter desc; ``` The common table expression (the part starting with `with letters ..`) act...
You can wrap query with inner select ``` select fl, count(*) from (select substr(p_nev,1,1) fl from pizza) group by fl order by fl desc; ``` In my practice optimizer always was subtle enough to make those queries equivalent in terms of execution plan
How to assign a name to a column - Oracle SQL
[ "", "sql", "oracle", "variables", "" ]
I have the following mySQL query which takes 26 seconds due to the count / avg function and GROUP BY (and this is without any records in the grouped on table: gemrating). Without the GROUP BY part of the query, it takes 0.1293 sec. Is there a way (e.g. temporary tables) to speed this up? I know one option is to save th...
Given your answer, and the fact that the subquery `rt` runs in .0010s, this query should work fine: ``` SELECT g.gemid as ggemid, g.title as gtitle, g.descr, g.userid as guserid, gemdetail.filename, g.dateentered as gdateentered, g.post, g.sort as gsort, g.grade as ggra...
Without the use of temp tables you should only need two scans over the data within your criteria to get each user's rating along with all users ratings for a gem. The example below is modified. If you have a proper index on gemid then this should return in milliseconds. However, as you add more fields into the results ...
Speed up a 26 second mysql query
[ "", "mysql", "sql", "performance", "optimization", "" ]
Let's say I have a table called "matches" where I save 2 teams from a soccer match. ``` ------------------------- | home_club | away_club | ------------------------- | | | ------------------------- ``` And I have a query that returns all the clubs from that table, both the home and away clubs thro...
If you want to know how many times each has appeared in the `matches` table, then you need to get rid of the `union` in the subquery. The `union` is going to remove duplicates. Here is how you would get a count: ``` select club, count(*) as NumAppears from (SELECT home_club AS club FROM matches UNION ALL ...
Try following ``` select sum(count) as Matches, Club from (select count(*) as count, home_club as Club from matches group by home_club union all select count(*) as count, away_club as Club from matches group by away_club ) a group by a.clubs ```
Count instances from a selected set of 2 unified columns
[ "", "sql", "" ]
In oracle 11g, I have a owner schema which contains the relevant tables required for an app. For my external application i am trying to create another user which should have select access on certain tables to the above schema. Lets call the owner schema A and the new schema B ``` create user B identified by blah; ...
You can create private synonyms for user B to use. As user B, run the following block: ``` begin FOR t IN (SELECT * FROM role_tab_privs WHERE grantee = 'SOME_ROLE' and owner = 'A') LOOP EXECUTE IMMEDIATE 'CREAETE SYNONYM ' || table_name || ' FOR A.' || table_name'; END LOOP; end; ```
if you are just *reading* data from tables owned by userB, you can set below command and run SELECT on tables as if they were in userA schema: ``` alter session set current_schema=userB ``` (logged as *UserA*) Then below two commands will be equivalent (have same result): ``` select ... from userB.TABLE1 select .....
Select access to all tables
[ "", "sql", "oracle", "plsql", "oracle11g", "" ]
I am reading the msdn topic about MERGE.<http://msdn.microsoft.com/en-us/library/bb510625.aspx> But it is very confusing for me. Let's say I have a table, ``` DECLARE @T Table ( ID INt, Name VARCHAR(10) ) ``` and I have, ``` MERGE INTO @T T1 USING (SELECT 4 AS ID) T2 ON (T1.ID = T2.ID) ``` `WHEN MATCHED TH...
I think of it in terms of branching records from both the `target` and `source` into different execution paths. Below I give an example of a simple list of numbers. I use a `full join` to represent the merge and `case` to represent the 'branching'. ``` DECLARE @source TABLE ( i INT, c CHAR(1) ) DECLARE @target TABLE ...
Merge basically will merge the data of two tables. If an ID field from the source table exists in the target table, it will do an `UPDATE` statement (`WHEN MATCHED THEN`). In case it does not exist, it will perform an `INSERT` (`WHEN NOT MATCHED BY TARGET`). `WHEN NOT MATCHED BY SOURCE` means there's a row in the targ...
Explain Merge SQL Statement in Simple Words?
[ "", "sql", "t-sql", "sql-server-2008-r2", "" ]
I have two tables, 'Product' and 'Product Packs'. One product can appear in many product packs and a product pack can have many products (A many to many relationship). I have also created a linking table to try and resolve this relationship but I am left with the following conundrum: ``` ------------------- | Linki...
You have a good starting point. Taking it here you should consider, making the two fields of the table into a composite primay key. That would prevent duplicate records as noted by @musical\_coder. You might also consider adding an integer column that indicates the quantity of products in the package. Finally, you m...
In my experience I would say that's no problem with this kind of relationship, but you need to be very careful when **analysing data**, but how you model is logical that a product is in a package and a package contains *n* products. So that's not bad.
Best way to normalize this data
[ "", "mysql", "sql", "database", "database-design", "" ]
Here is my sample table ``` Col1 Col2 A 1 B 1 A 1 B 2 C 3 ``` I want to be able to select distinct records where all rows have the same value in Col1 and Col2. So my answer should be ``` Col1 Col2 A 1 C 3 ``` I tried ``` SELECT Col1, Col2 FROM Table GROUP BY Col1, Col2...
Try this out: ``` SELECT col1, MAX(col2) aCol2 FROM t GROUP BY col1 HAVING COUNT(DISTINCT col2) = 1 ``` Output: ``` | COL1 | ACOL2 | |------|-------| | A | 1 | | C | 3 | ``` Fiddle [here](http://sqlfiddle.com/#!2/63c72/1). Basically, this makes sure that amount the different values for `col2` are uni...
Try this: ``` SELECT * FROM MYTABLE GROUP BY Col1, Col2 HAVING COUNT(*)>1 ``` For example SQLFiddle [here](http://sqlfiddle.com/#!3/d98c8b/2)
Select records where all rows have same value in two columns
[ "", "sql", "sql-server-2008", "" ]
this is a huge problem i've to solve in sql but i don't know how. This is my dataset: ``` customer; publisher; qty ``` This is a data sample: ``` CustA; PublX; 10 CustA; PublZ; 20 CustA; PublF; 30 CustB; PublX; 8 CustC; PublD; 9 CustD; PublX; 9 CustD; MyPub; 18 CustE; PublZ; 3 CustE; MyPub; 8...
You can use `NOT IN` with a sub query: ``` SELECT customer, publisher, qty FROM books WHERE customer NOT IN ( SELECT DISTINCT customer FROM books WHERE publisher = 'MyPub' ) ``` [**SQL Fiddle Demo**](http://sqlfiddle.com/#!2/b42bb/3/0...
Maybe this: ``` SELECT * FROM myTable WHERE customer NOT IN (SELECT customer FROM myTable WHERE Publisher = "MyPubl") ``` Or if you just want the customers ``` SELECT DISTINCT customer FROM myTable ```
How to get only row without a specific value in a column
[ "", "mysql", "sql", "" ]
I would like initialize a H2 database, but I am not sure if the records exist. If they exist I don't want to do anything, but if they don't exist I would like to write the default values. Something like this: ``` IF 'number of rows in ACCESSLEVELS' = 0 INSERT INTO ACCESSLEVELS VALUES (0, 'admin'), (1, 'SEO'),...
The following works for MySQL, PostgreSQL, and the H2 database: ``` drop table ACCESSLEVELS; create table ACCESSLEVELS(id int, name varchar(255)); insert into ACCESSLEVELS select * from ( select 0, 'admin' union select 1, 'SEO' union select 2, 'sales director' union select 3, 'manager' union select 4, 'REP' ) x wher...
``` MERGE INTO ACCESSLEVELS KEY(ID) VALUES (0, 'admin'), (1, 'SEO'), (2, 'sales director'), (3, 'manager'), (4, 'REP'); ``` Updates existing rows, and insert rows that don't exist. If no key column is specified, the primary key columns are used to find the row. If you do not name the columns, their values...
H2 SQL database - INSERT if the record does not exist
[ "", "sql", "h2", "" ]
I am working with a query: ``` SELECT DISTINCT PointPerson FROM DailyTaskHours WHERE ActivityDate BETWEEN @startDateParam AND @endDateParam GROUP BY PointPerson HAVING SUM([Hours]) > 0 ORDER BY PointPerson ``` This is what it is returning: ![enter image description here](https://i.stack.imgur.com/6C8Vr.png) ...
You just add a condition in your `WHERE` clause ``` SELECT DISTINCT PointPerson FROM DailyTaskHours WHERE ActivityDate BETWEEN @startDateParam AND @endDateParam AND PointPerson <> '' GROUP BY PointPerson HAVING SUM([Hours]) > 0 ORDER BY PointPerson ``` There are lot of variations of this condition, depending on h...
``` SELECT DISTINCT PointPerson FROM DailyTaskHours WHERE ActivityDate BETWEEN @startDateParam AND @endDateParam AND len(ltrim(rtrim(PointPerson)))>0 GROUP BY PointPerson HAVING SUM([Hours]) > 0 ORDER BY PointPerson ```
Not SELECTing a row if it is empty
[ "", "sql", "sql-server", "" ]
i am trying to update a table but my problem is the target table has duplicate records so my update is failing for that reason. This is the error: attempt to update a target row with values from multiple join rows. I know when updating a table, we have to join unique keys but i cannot delete the duplicates from the tab...
Try writing it with an `IN` clause: ``` UPDATE CUSTOMERTABLE SET SERVICE = 'BILLING' WHERE CUSTOMERTABLE.ACCOUNT_NUMBER IN (SELECT CUSTOMER_ID FROM CUSTOMER_RELATION ED JOIN STG_CUSTOMER_REV TXN ON ED.CUSTOMER_ID = TXN.CUS_ID) ```
Here is another option, which probably has a better performance compared to an `IN` solution if `CUSTOMER_RELATION` or `STG_CUSTOMER_REV` are large tables. ``` UPDATE C SET SERVICE = 'BILLING' FROM CUSTOMERTABLE C WHERE EXISTS (SELECT 1 FROM CUSTOMER_RELATION ED, STG_CUSTOMER_REV TXN WH...
update table where there is duplicate records using sql
[ "", "sql", "sql-server", "t-sql", "" ]
I'm getting an error when trying to run this query: ``` UPDATE tbl1, tbl2 SET `tb1`.field=SUM(tbl2.grade) WHERE tbl2.word=tbl1.word ``` This is the error: `#1111 - Invalid use of group function` I basically trying to get the sum of a field from tbl2 and insert it into tbl1
The easiest way to achieve what you want to do is via a subquery: ``` UPDATE tbl1 SET tbl1.field= (SELECT SUM(tbl2.grade) FROM tbl2 WHERE tbl2.word=tbl1.word) ``` You're selecting multiple values from tbl2 and want the sum of them for each entry in tbl1.
Join against a subquery that calculates the total grade for every word. ``` UPDATE tbl1 a INNER JOIN ( SELECT word, SUM(grade) totalGrade FROM tbl2 GROUP BY word ) b ON a.word = b.word SET a.field = b.totalGrade ```
#1111 - Invalid use of group function
[ "", "mysql", "sql", "" ]
I have a problem with my stored procedure in SQL Server 2012. First the table : ``` [ProductId] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](100) NOT NULL, [Description] [nvarchar](500) NOT NULL, [Category] [nvarchar](50) NOT NULL, [Price] [decimal](16, 2) NOT NULL, ``` and the stored procedur...
All output options from a case must be of the same datatype, I think the case decides what output type to use from the first option, and attempts to cast the other values to that type, In your case, the first and last options, (ProductId and Price), are numeric, buit the others are character... modify the case (in both...
I think it is because of your `CASE` expression. First line of your case is `WHEN 'ProductId' THEN ProductId` and therefore it is converting every other field to the same datatype as `ProductId`. It *works for* `Price` as Price can be converted as INT but *fails for* `Name` *as* `it encounters an error converting data ...
Stored procedure and bad data type nvarchar to numeric
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I know how to brute-force a solution to this; I'm mostly looking for an elegant solution to increase my own knowledge for the future. I have a data table with 20 code flag fields. (CODE\_01, CODE\_02, CODE\_03, ..., CODE\_20) I am looking for records where *any* of those code columns contain certain values (eg: 11, 1...
Although I agree with @GorndonLinoff that creating a `code` table would probably be the "right" solution, here's a trick you could try without changing your tables' structure: If the relevant values are known when you're writing the query, you can replace the inline list with a set of `UNION`-ized queries from `dual`,...
I have no idea if this would be faster, but you might try ``` select * from table t where exists (Select * From (Select PK, CODE_01 code from table Union Select PK, CODE_02 code from table Union Select PK, CODE_03 code from table Union Select PK, CODE_04 code from table Union ... Select P...
Oracle SQL: Selecting records where multiple columns could contain multiple values
[ "", "sql", "oracle", "" ]
Is there a way to see what character(s) replace the %/wildcard in an SQL Query? Say ``` $exhibitions = $wpdb->get_results( "SELECT * FROM wp_postmeta WHERE meta_key LIKE 'dates_%_startdate' ORDER BY meta_value LIMIT 0 , 30" ); ``` If the meta\_key-column in a result was '...
``` SELECT *, replace(replace(meta_key, 'dates_', ''), '_startdate', '') FROM wp_postmeta WHERE meta_key LIKE 'dates_%_startdate' ORDER BY meta_value LIMIT 0 , 30 ``` ## [SQLFiddle demo](http://sqlfiddle.com/#!2/d41d8/24457)
Just a warning, in MSSQL an underscore is a Single Character wildcard. <http://technet.microsoft.com/en-us/library/ms179859.aspx> Also in MySQL appearently: <http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html>
See what wildcard what used in SQL Query
[ "", "sql", "" ]
I want to get a backup of a single table with its data from a database in SQL Server using a script. How can I do that?
There are many ways you can take back of table. 1. BCP (BULK COPY PROGRAM) 2. Generate Table Script with data 3. Make a copy of table using SELECT INTO, example [here](https://stackoverflow.com/a/22608120/290343) 4. SAVE Table Data Directly in a Flat file 5. Export Data using SSIS to any destination
``` SELECT * INTO mytable_backup FROM mytable ``` This makes a copy of table `mytable`, and every row in it, called `mytable_backup`. (It will not copy any indices, constraints, etc. Just the structure and data). (It will fail if you have an existing table named `mytable_backup`, so if you want to use this code regu...
Backup a single table with its data from a database in sql server 2008
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I want to get the name of the employee who has the minimum salary. Is there a way to do this using only one query? I have given my query below, it doesn't work because the having clause requires a condition. Is there any way to give a condition in the having clause that will retreive the employee name with the minimum ...
How about using `ROWNUM`? ``` SELECT * FROM(SELECT first_name, salary FROM Employees ORDER BY salary ) WHERE ROWNUM = 1 ```
``` SELECT first_name, salary as "sal" FROM employees WHERE salary =(SELECT MIN(salary) FROM employees); ```
Using the MIN function in the having clause
[ "", "sql", "oracle", "min", "having", "" ]
Goal - List average salary for men and average salary for women for each department. Show department name and number. ``` select AVG(salary) as 'Avg salary for men' From [Enterprise].[dbo].[Employee]JOIN [Enterprise].[dbo].[Department] ON Employee.EMPNO = Department.deptNo where SEX = 'm' ``` Still learnin...
As pointed out, your join condition doesn't make sense, you are joining an employee number to a department number, which wouldn't match (or would, but wouldn't achieve the logic you desire). ``` SELECT d.name , AVG(e_man.salary) avg_man , AVG(e_woman.salary) avg_woman FROM department d LEFT OUTER JOIN employee e_man...
I'm going to assume you meant to join by `deptNo`. ``` SELECT Department.Name, AVG(salary) as 'Avg salary for men' FROM [Enterprise].[dbo].[Employee] JOIN [Enterprise].[dbo].[Department] ON Employee.deptNo= Department.deptNo WHERE SEX = 'm' GROUP BY Department.Name ``` This will show the average for each department ...
SQL server query joins
[ "", "sql", "join", "outer-join", "" ]
How can I modify the below query to **limit the number of rows fetched PER `userid` from the `post_list` table** without affecting the performance of the script (the post\_list table is over 10,000 rows here) ? ``` $sql = query("SELECT userid, post, post_id, id, username FROM post_list, users WHERE post_list.userid =...
``` SELECT pl.*, u.* FROM users AS u JOIN ( SELECT userid, SUBSTRING_INDEX(GROUP_CONCAT(post_id ORDER BY post_id DESC), ',', 5) AS last_5_posts FROM post_list GROUP BY userid ) AS pl5 ON(u.id = pl5.userid) JOIN post_list AS pl ON (FIND_IN_SET(pl.post_id, pl5.last_5_posts)) ORDER BY pl.post_...
Use [`LIMIT`](http://dev.mysql.com/doc/refman/5.0/en/select.html) ``` ORDER BY post_id LIMIT 5; ``` --- As you commented, you can take a look at this article [here](http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/) which will explain you in detail, *How to select the first/l...
SELECT query with COUNT and HAVING BY
[ "", "mysql", "sql", "" ]
I have a table of 32,589 rows, and one of the columns is called 'Location' and is a `Varchar(40)` column type. The column holds a location, which is actually a suburb, all uppercase text. A function that uses this table does a: ``` IF EXISTS(SELECT * FROM MyTable WHERE Location = 'A Suburb') ... ``` Would it be bene...
Without an index SQL Server will have to perform a table scan to find the first instance of the location you're looking for. You might get lucky and have the value be in one of the first few rows, but it could be at row 32,000, which would be a waste of time. Adding an index only takes a few second and you'll probably ...
I concur with @Brian Shamblen answer. Also, try using TOP 1 in the inner select `IF EXISTS(SELECT TOP 1 * FROM MyTable WHERE Location = 'A Suburb')` You don't have to select all the records matching your criteria for `EXISTS`, one is enough.
Index on VARCHAR column
[ "", "sql", "sql-server", "" ]
I am trying to use a NULLIF function to return a NULL value where the divisor of my query results in zero and therefore returns a divide by zero error. However, I'm having trouble wrapping the function around my statement. The statement contains a CAST, CASE and SUM function. I've wrapped the function around the diviso...
The syntax you posted is invalid and hard to read, also it seems your logic is wrong. Try this instead: ``` declare @stuyear int = 11 select cast( sum( case when @StuYear=11 and [Levels of Progress] < 3 or @StuYear=10 and [Levels of Progress] < 2 or @StuYear=9 and [Levels...
``` Cast( Sum( CASE WHEN (@StuYear = 11 AND [Levels of Progress] < 3) OR (@StuYear = 10 AND [Levels of Progress] < 2) OR (@StuYear = 9 AND [Levels of Progress] < 1) THEN 1 ELSE 0 END ) , As decimal) / NullIf( Cast( Sum( CASE WHEN [Levels of Progress] IS NULL ...
SQL NULLIF Function not working around divisor
[ "", "sql", "sql-server-2008", "null", "divide-by-zero", "" ]